Node JS HTTP Server request.on('data') event failure - javascript

I am working on a NodeACS app in which I have to send xml as request from Java HTTP client and to receive response after some manipulation. The Java HTTP Client is working fine so far but the issue is with Node JS file. The req.on('data'...) event is not firing in my case.
Following is the code of my JS file:
function index(req, res) {
console.log(req.headers); //Its getting printed on console
req.on('data', function (data) {
console.log("Inside 1"); //Not printed on console
....REST OF THE CODE....
});
req.on('end', function () {
res.writeHead(200);
res.end();
});
}
In the above code after getting request the index function is called and printing the output for console.log(req.headers); but as mentioned above the script is not running after that. Please help me out What am I missing in this.
For testing I have installed cURL on my system and sending POST request to server using cURL request using following command:
curl -X POST -d #output.xml http://localhost:7788/

Can you confirm you aren't consuming the body prior to this? If the body has been consumed already by another middleware like body-parser you would need to restream the body via something like connect-restreamer. If it were consumed, the data event would not be emitted.
If that checks out, check to see if the "end" event is being emitted. Could be a sign of the content-length header being set to the wrong value.

Related

NodeJS HTTP response.redirect dosen't exist?

I tried to do a little test and redirect to google instantly but it says that response.redirect dosen't exist
Here's my code:
function Server(req, res) {
res.redirect('http://www.google.com');
res.end();
}
var server = http.createServer(Server);
server.listen(8080);
console.log('Server is running...');
The error im getting:
TypeError: res.redirect is not a function
There is no such method on http.ServerResponse (see the manual).
You've most likely read documentation from the express project, a popular web server framework, which has a redirect method on the response object.
Write the appropriate headers manually instead
response.writeHead(302, {
'Location': 'your/path.html'
});

Unexpected "write after end" error in express

I am trying to proxy an api call from client side through my server for some third party service, reasons for this being CORS issues and adding in a secret key on the server side. I usually get it done in the following way:
app.use('/someService', (req, res) => {
let url = `https://example.com/${config.SECRET_KEY}/endpoint${req.url}`
req.pipe(request(url).pipe(res))
})
this way I can use any ajax library on the client side and perform get request for example: get: '/someService/params' and it would normally go through and perform that request and then pipe it back. However now I started getting:
Error: write after end
in express and I am not entirely sure about what could be causing it.
Your piping is wrong. As it is now, you're piping to res twice (.pipe() returns the argument passed to it for chainability).
Instead try this:
req.pipe(request(url)).pipe(res)
I should point out however that properly proxying the HTTP response is not quite that simple since currently this line will always respond with HTTP status code 200, no matter what the remote server for the middle request responds with. Also, any headers from that response will not be sent to res. With that in mind, you could naively try something like:
var proxiedRes = req.pipe(request(url));
proxiedRes.on('response', function(pres) {
res.writeHead(pres.statusCode, pres.headers);
// You will want to add a `pres` 'error' event handler too in case
// something goes wrong while reading the proxied response ...
pres.pipe(res);
});

Facebook Messanger Bot Webhook issue

I received this message
Your Webhooks subscription callback URL has not been accepting
updates.
We've noticed that your Webhooks subscription for callback URL
https://trololo.herokuapp.com/bot has not been accepting updates
for at least 16 minutes. Please verify that your callback server is
functioning so you may continue to receive updates. If you need to
update your callback URL, see
https://developers.facebook.com/docs/graph-api/reference/app/subscriptions#update
If your callback URL continues to fail to accept updates for 8 hours
straight, we will disable your subscription. To reactivate the
subscription, make a POST request with the same parameters, and it
will be reactivated.
This code is executed on the server
app.post('/bot', function (req, res) {
console.log('post bot: ' + req);
var messaging_events = req.body.entry[0].messaging;
for (var i = 0; i < messaging_events.length; i++) {
var event = req.body.entry[0].messaging[i];
var sender = event.sender.id;
if (event.message && event.message.text) {
text = event.message.text;
console.log('text received: ' + text);
sendTextMessage(sender, "Text received, echo: "+ text.substring(0, 200));
}
}
res.sendStatus(200);
});
But it fails because req.body is undefined. The req params is also no json because it makes this error:
TypeError: Converting circular structure to JSON
req only shows [object Object] and I have no idea whats inside the object. .toString isn't working either.
I made the complete guide twice. I think the issue comes from the part were the facebook page should connect to the facebook app. I do this with curl -ik -X POST "https://graph.facebook.com/v2.6/me/subscribed_apps?access_token=<mytoken>" Please help. Any response is greatly appreciated.
Here is a demo log
I think it's a dependency problem... maybe you're missing the json body parser body-parser
If you look at comments on program sample on node-wit/examples/messenger.js, you will see that you need install some deps:
in your project directory, try:
npm install body-parser express request
And look at: https://www.youtube.com/watch?v=zFO1cRr5-qY ... I think they resolved exactly this issue and others that you may find.

Unexpected End of Input - curl JSON on Express/Node App

I have an Express/Node app that is deployed to a Heroku instance. The app has a POST api endpoint that expects a .json file, reads the data, and populates the app with the JSON data. Below is the backend code that handles the POST request:
router.route('/data')
.post(function (req, res) {
return DataUtils.storeData(req, res);
});
Utils.storeData = function (req, res) {
req.pipe(req.busboy);
req.busboy.on('file', function (fieldname, file, filename) {
file.on('data', function(data) {
var data;
try {
data = JSON.parse('' + data); // quick casting into a String
var numPersonSessionObj = data.length;
...
// etc etc...
When we try to make the request via the curl command below:
curl -H "Content-Length: 5567" -F file=#sample_data/sample_json.json
http://[heroku-instance]/api/data
The server sometimes works fine, and uploads the data, and other times, throws an "Unexpected end of input" error. It seems as though the buffer method we're using is not reading all of the data for some reason. Upon logging the data.length in the code above (i.e. the JSON), it seems as though the request fails whenever the data length is less than its supposed to be. Is there something wrong with how I'm reading in the JSON file above? Thanks--
The data event only indicates that some data was received – not that all data was received. You want to wait for the end event before parsing your JSON. See this example from the official documentation for further details: https://nodejs.org/api/stream.html#stream_api_for_stream_consumers
Content-Length must be the count of octets the response body.
if you try using the value of
data.length
rather than
Buffer.byteLength(data)

My http.createserver in node.js doesn't work?

Hello guys i just started learning node.js today and search a lot off stuff on the internet , then try to code in node.js i use these two codes to show me the same result but the last one is show the error on my browser something likes "can not find the page".So please explain to me why?
// JScript source code
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
}).listen(1337, "127.0.0.1");
console.log('Server running at http://127.0.0.1:1337/');
This is working but
// Include http module.
var http = require("http");
// Create the server. Function passed as parameter is called on every request made.
// request variable holds all request parameters
// response variable allows you to do anything with response sent to the client.
http.createServer(function (request, response) {
// Attach listener on end event.
// This event is called when client sent all data and is waiting for response.
request.on("end", function () {
// Write headers to the response.
// 200 is HTTP status code (this one means success)
// Second parameter holds header fields in object
// We are sending plain text, so Content-Type should be text/plain
response.writeHead(200, {
'Content-Type': 'text/plain'
});
// Send data and end response.
response.end('Hello HTTP!');
});
}).listen(1337, "127.0.0.1");
This one is not working
Why?
The link of the last one that's not working
http://net.tutsplus.com/tutorials/javascript-ajax/node-js-for-beginners/
Thank you for all the answers, but i still don't understand about the problems.
the last one that is not working just has request.on?
request is an instance of http.IncomingMessage, which implements the stream.Readable interface.
Documentation at http://nodejs.org/api/stream.html#stream_event_end says:
Event: 'end'
This event fires when no more data will be provided.
Note that the end event will not fire unless the data is completely consumed. This can be done by switching into flowing mode, or by calling read() repeatedly until you get to the end.
var readable = getReadableStreamSomehow();
readable.on('data', function(chunk) {
console.log('got %d bytes of data', chunk.length);
})
readable.on('end', function() {
console.log('there will be no more data.');
});
So in your case, because you don't use either read() or subscribe to the data event, the end event will never fire.
Adding
request.on("data",function() {}) // a noop
within the event listener would probably make the code work.
Note that using the request object as a stream is only necessary for when the HTTP request has a body. E.g. for PUT and POST requests. Otherwise you can consider the request to have finished already, and just send out the data.
If the code your posting is taken literally from some other site, it may be that this code example was based on Node 0.8. In Node 0.10, there have been changes in how streams work.
From http://blog.nodejs.org/2012/12/20/streams2/
WARNING: If you never add a 'data' event handler, or call resume(), then it'll sit in a paused state forever and never emit 'end'.
So the code you posted would have worked on Node 0.8.x, but does not in Node 0.10.x.
The function you are applying to the HTTP server is the requestListener which supplies two arguments, request, and response, which are respectively instances of http.IncomingMessage and http.ServerResponse.
The class http.IncomingMessage inherits the end event from the underlying readable stream. The readable stream is not in flowing mode, so the end event never fires, therefore causing the response to never be written. Since the response is already writable when the request handler is run, you can just directly write the response.
var http = require('http');
http.createServer(function(req, res) {
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end('Hello HTTP!');
}).listen();

Categories

Resources