I have a NodeJS server script, which works like a charm on my local dev environment. But in (beta) production the webserver times out at every request. I've set this up fairly straight forward but I'm unsure how to fix it - or even where to look for a solution. Below is a simplified implementation, my logic for handling post request has been removed. What am I overlooking?
var requestListener = '';
// define the request listener, to handle incoming requests
requestListener = function (req, res) {
try {
if (req.method == 'POST') {
var queryString = '';
req.on('data', function (data) {
queryString += data;
});
req.on('end', function () {
// my logic is in here
res.end(JSON.stringify({ err: false, msg: 'all fine' }));
});
}
res.writeHead(200);
res.end();
} catch (error) {
res.writeHead(400);
res.end(error);
}
}
// boot the webserver
server = http.createServer(requestListener);
server.listen(8080);
Related
I have a fairly simple express server that is designed to take external client data and publish it via mqtt to a gateway. It works perfectly with a hardcoded variable but I can't figure out how to extract the actual data from the POST request, which is as follows (it prints to the console just fine):
const postData = app.post('/send-data', function (req, res) {
console.log('connected', req.body);
res.status(200).json(req.body)
});
I need to get the req.body data out of that and into the following code that publishes the data to the topic:
client.on('connect', function () {
console.log('connected!');
client.publish('iot-2/type/wtlType/id/channel100/evt/event/fmt/json', publishData);
client.end();
});
publishData will just be the stringified json response.
This is the create server code if that helps:
https.createServer(options, app).listen(30002, () => {
console.log('Listening')
});
If I understand correctly your question is about the logic of getting the req.body published by the client. If so, then something like this should work:
let connected = false;
client.on('connect', function () {
console.log('connected!');
connected = true;
});
const postData = app.post('/send-data', function (req, res) {
console.log('connected', req.body);
res.status(200).json(req.body)
client.publish('iot-2/type/wtlType/id/channel100/evt/event/fmt/json', JSON.stringify(req.body));
client.end(); // are you sure you want this? can there not be more messages to broadcast?
});
I want to write a simple Node Js application which will capture and re-transmit http/https request to Browser?
I have written the below code, but it works only for http request.
var server = http.createServer(function (req,res) {
console.log("start request:", req.url);
var option = url.parse(req.url);
option.headers = req.headers;
var proxyrequest = http.request(option, function (proxyresponce) {
proxyresponce.on('data', function (chunk) {
console.log("proxy responce length" ,chunk.length);
res.write(chunk,'binary');
});
proxyresponce.on('end',function () {
console.log("proxy responce ended");
res.end();
});
res.writeHead(proxyresponce.statusCode, proxyresponce.headers);
});
});
I'm trying to build a slack app and to configure it properly I need to do successive Https get request. I use callbacks methods to handle it, the first one calls the second one without any problem but then the third one never starts, and my program is stuck.
Here is my code :
//CREATE THE app OBJECT
//---------------------
var app = express();
app.use(bodyParser());
var port = process.env.PORT || 5000;
//CALLBACK FUNCTIONS
//------------------
// USE THE SLACK BUTTON TO CREATE THE APP
boutonSlack = function(req, res,next) {
res.send('<a href="https://slack.com/oauth/authorize?scope=bot,incoming-webhook,commands&client_id='+process.env.CLIENT_ID+'">'
+'<img alt="Add to Slack" height="40" width="139"'
+'src="https://platform.slack-edge.com/img/add_to_slack.png" '
+'srcset="https://platform.slack-edge.com/img/add_to_slack.png 1x, '
+'https://platform.slack-edge.com/img/add_to_slack#2x.png 2x" /></a>');
console.log('cb0:le bouton slack s\'affiche');
next();
app.get('/redirect/',oauthFlow);
};
//GET THE CODE PARAMETER AND PERFORM THE OAUTH FLOW
oauthFlow = function(req, res, next){
process.env.CODE = req.query.code;
console.log('cb1 : le code est récupéré');
https.get('https://slack.com/api/oauth.access?client_id='+process.env.CLIENT_ID+'&client_secret='+process.env.CLIENT_SECRET+'&code='+process.env.CODE, (res) => {
res.on('data', (chunk) => {
var result = JSON.parse(chunk);
process.env.SLACKTOKEN = result.access_token;
process.env.SLACK_BOT_TOKEN = result.bot.bot_access_token;
console.log('cb2 : le token est récupéré')
next();
app.get('/websocket/',ouvertureWebsocket);
});
});
};
//THIS CALLBACK NEVER STARTS
//PERFORM THE rtm.slack METHOD
ouvertureWebsocket = function (req, res, next) {
console.log("working");
https.get('https://slack.com/api/rtm.start?token='+process.env.SLACK_BOT_TOKEN, (res) => {
res.on('data', (chunk) => {
var result = JSON.parse(chunk);
console.log(JSON.stringify(result));
console.log('cb3 : ouverture du web socket');
next();
});
});
res.end();
}
//RUN THE CALLBACK FUNCTIONS
//--------------------------
app.get('/',boutonSlack);
app.listen(port, function () {
console.log('Ready, listenning port '+port);
});
This raises suspicions:
app.get('/redirect/',oauthFlow);
not that theres anything wrong with the code line, it's just that its inside a handler for the '/' route. Normally you'd define all route handlers on the top level and not anymore in any handlers.
I'm trying to build a reverse proxy in front of a Couchbase SyncGateway. Before sending requests to the sync gateway, I'd like to send them to an authentication server for authentication, then if all is good, send the request on (unmodified from original) to the sync gateway. The database is not staying up to date with the client modifications and I believe this is because I am not successfully proxying PUT/POST requests. Here is the code I have:
var http = require('http');
var httpProxy = require('http-proxy');
var apiProxy = httpProxy.createProxyServer();
var request = require('request').defaults({json: true});
var authServer = 'http://authserverdns:5000';
var syncGateway = 'http://syncgatewaydns:4984';
http.createServer(function (req, res) {
if (req.method == 'POST' || req.method == 'PUT') {
req.body = '';
req.addListener('data', function(chunk) {
req.body += chunk;
});
req.addListener('end', function() {
processRequest(req, res);
});
} else {
processRequest(req, res);
}
}).listen(8080);
function processRequest(req, res) {
request(authServer, function(error, response, body) {
if (body.authenticated) {
console.log('authenticated !!!');
apiProxy.web(this.req, this.res, {target: this.sg});
} else {
console.log('request denied !!!');
}
}.bind({req: req, res: res, sg: syncGateway}));
}
At first I was using an express server and having same issue. As I looked into the problem, it looks like maybe there is an issue with Express and proxying PUT/POST requests. So, I attempted to use some examples out there and this is what I've ended up with, but still not working. Any ideas as to where I'm going wrong here? Authenticated prints, so I know I'm getting to the point of proxying. And the sync gateway seems to be fine with the GET requests.
Thanks
ugh. I wasn't adding the rest of the URL to the forwarding address for the Sync Gateway. The post here helped.
I'm new to node.js. Trying to get a console to print when the request ends. I try to go to localhost:8080 and also localhost:8080/ but nothing prints in the terminal. Any idea why? Doing this because when I run this example because when I try to run the demo at http://tutorialzine.com/2012/08/nodejs-drawing-game/ the terminal says socket started but it does not render the index.html page. So I can't figure out why this code to serve static files for other is not working for me.
var static = require('node-static');
//
// Create a node-static server instance to serve the './public' folder
//
// var file = new(static.Server)('./');
require('http').createServer(function (request, response) {
request.addListener('end', function () {
console.log("ended");
});
}).listen(8080);
It seems that your are using Node.js 0.10.x and in the new version you have to resume the readable streams to make them emit events:
require('http').createServer(function (request, response) {
var body = '';
request.setEncoding('utf8');
request.on('readable', function () {
body+= this.read();
}
request.on('end', function () {
console.log('ended');
console.log('Body: ' + body);
});
request.resume();
}).listen(8080);
You should be call node-static serve inside the request handler so that you can get index.html
var static = require('node-static');
var fileServer = new static.Server('./');
require('http').createServer(function (request, response) {
fileServer.serve(request, response); //add this line
request.addListener('end', function () {
console.log("ended");
});
}).listen(8080);