no req.body sent on POST requests

青春壹個敷衍的年華 提交于 2020-01-06 18:10:58

问题


After reading many similar threads, I failed to see the reason of my problem...

Im trying to learn how to create a RESTful API with node and express 4, pretty basic and simple, but when i try to save my document with a POST req, no req.body is sent on the request and i have some problems.

Lets look a little piece of code:

module.exports = (router, Bear) ->
  router.route '/bears'
    .get (req, res) ->
      Bear.find (err, bears) -> if err then err else res.json bears

    .post (req, res) -> 
      newBear =
        _id: req.body.bearId
        nombre: req.body.nombre
      bear = new Bear(newBear)
      bear.save (err) ->
        if err then res.send err 
        # res.json msg: "#{bear.nombre}, creado"
        res.json msg: "created"

So far, this is my basic routes config (for now). The server is:

express = require 'express'
app = express()
morgan = require 'morgan'
bodyParser = require 'body-parser'
mongoose = require 'mongoose'

app.use bodyParser.urlencoded extended: true
app.use bodyParser.json()
app.use morgan 'dev'

require('./app/config/js/database')(mongoose)

router = express.Router()
Bear = require './app/models/js/bear'

router.get '/', (req, res) -> res.json msg: 'It works'

require('./app/routes/js/bears')(router, Bear)

app.use '/api', router

port = 8080

app.listen(port)
console.log("Corriendo en #{port}")

And the other pieces of code are not relevant here (i think), so, when i send a request using postman, or CURL, i get always a {} response and a crash message on my server:

home/nano/Dev/bears/node_modules/mongoose/lib/utils.js:413
        throw err;
              ^
Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (http.js:689:11)
    at ServerResponse.header (/home/nano/Dev/bears/node_modules/express/lib/response.js:662:10)
    at ServerResponse.send (/home/nano/Dev/bears/node_modules/express/lib/response.js:146:12)
    at ServerResponse.json (/home/nano/Dev/bears/node_modules/express/lib/response.js:235:15)
    at Promise.<anonymous> (/home/nano/Dev/bears/app/routes/js/bears.js:22:20)
    at Promise.<anonymous> (/home/nano/Dev/bears/node_modules/mongoose/node_modules/mpromise/lib/promise.js:172:8)
    at Promise.emit (events.js:95:17)
    at Promise.emit (/home/nano/Dev/bears/node_modules/mongoose/node_modules/mpromise/lib/promise.js:84:38)
    at Promise.reject (/home/nano/Dev/bears/node_modules/mongoose/node_modules/mpromise/lib/promise.js:111:15)
    at Promise.error (/home/nano/Dev/bears/node_modules/mongoose/lib/promise.js:95:15)

Really i have no idea I really have no idea what to do, I have all afternoon and into the night in this.

Well, i make the changes in the code and now the traceback desapeared but the request still going empty.

module.exports = (router, Bear) ->
  router.route '/bears'
    .get (req, res) ->
      Bear.find (err, bears) -> 
        if err then return res.send err 
        res.json bears

    .post (req, res) -> 
      newBear =
        _id: req.body.bearId
        nombre: req.body.nombre
      bear = new Bear(newBear)
      bear.save (err) ->
        if err then return res.send err
        res.json msg: "created"

The JS code:

(function() {
  module.exports = function(router, Bear) {
    return router.route('/bears').get(function(req, res) {
      return Bear.find(function(err, bears) {
        if (err) {
          return res.send(err);
        }
        return res.json(bears);
      });
    }).post(function(req, res) {
      var bear, newBear;
      newBear = {
        _id: req.body.bearId,
        nombre: req.body.nombre
      };
      bear = new Bear(newBear);
      return bear.save(function(err) {
        if (err) {
          return res.send(err);
        }
        return res.json({
          msg: "created"
        });
      });
    });
  };

}).call(this);

I'm sending the request via RESTClient for Firefox, Curl, Postman ... the content type header is Content-Type: application/json; charset=utf-8


回答1:


If you comment out:

Bear = require './app/models/js/bear'

and replace:

require('./app/routes/js/bears')(router, Bear)

with:

router.post "/bears", (req, res, next) ->
  console.log req.body
  res.json req.body
  return

you will see that the req.body is coming through.

As mentioned in the comments, there is a missing return statment in your bears.coffee route file. You need to change line 12 so that it reads:

if err then return res.send err

Make sure that you are sending your parameters in the body of the request. For curl you should use:

curl -X POST -d "bearId=1221&nombre=papa" http://localhost:8080/api/bears

For Postman, make sure you choose POST from the dropdown and that you click on x-www-form-urlencoded and put your parameters in the "Key" and "Value" fields respectively.



来源:https://stackoverflow.com/questions/26227843/no-req-body-sent-on-post-requests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!