开发者

Node.js HTTP: request 'end' event is never called

开发者 https://www.devze.com 2023-03-18 08:55 出处:网络
I have a client that is sending data chunks to my node.js server. I want to listen on the \"end\" event and retrieve the accumulated request body.

I have a client that is sending data chunks to my node.js server.

I want to listen on the "end" event and retrieve the accumulated request body.

Here is my code:

app.post('/users', function(req, res){

  req.on('end', function() { // WHY 开发者_JS百科IS THIS NEVER FIRED?
    console.log(req.body);

    res.send({
      "status": "ok"
    });

  });

});

The problem is that the 'end' event is never fired.

Anyone knows why?

Also, if I do in this way, will the req.body be the accumulated body of all the body chunks?


Basically http POST only fires when you POST to the server. I can't be certain, but I'm assuming you are just attempting to visit server:port/users in your web browser and fail to get a response. By default the web browser is GETing the server. To fix this you have two options.

1. If you change app.post to app.get the event will correctly fire when you visit /users

2. Or you can fire the post function using a form. For example the following code will display a form if you visit the page using GET. When you submit the form it will fire POST.

var express = require('express'),
    app = express.createServer();

app.listen(1337, "127.0.0.1");

app.get('/users',function(req,res){
  res.send('<form method="post" action="/users"><input type="submit" value="Submit" /></form>');
})

app.post('/users', function(req, res){
  req.on('end', function() {
    console.log('success');
    res.send('success!!!');
  });
});


I encountered the same problem, and found this discussion helpful: My http.createserver in node.js doesn't work?

Simply put, by inserting the line: request.on("data",function() {}) inside the .createServer loop but after the request.on loop made it work.

0

精彩评论

暂无评论...
验证码 换一张
取 消