POST请求未发送任何请求正文 [英] no req.body sent on POST requests

查看:104
本文介绍了POST请求未发送任何请求正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读了许多类似的主题之后,我看不到问题的原因...

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

我正在尝试学习如何使用node和express 4创建RESTful API,这是非常简单和基本的,但是当我尝试使用POST req保存文档时,没有req.body被发送给请求,并且我有一些请求问题.

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.

让我们看一些代码:

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}")

其他代码与这里无关(我认为),因此,当我使用邮递员或CURL发送请求时,我的服务器上总是收到{}响应和崩溃消息:

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"

JS代码:

(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);

我正在通过RESTClient发送用于Firefox,Curl,Postman的请求...内容类型标头为Content-Type: application/json; charset=utf-8

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

推荐答案

如果您将其注释掉:

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

并替换:

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

具有:

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

您会看到req.body正在通过.

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

如评论中所述,您的 bears.coffee 路由文件中缺少返回陈述.您需要更改第12行,使其显示为:

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

对于邮递员,请确保从下拉列表中选择POST,然后单击x-www-form-urlencoded,然后将参数分别放在键"和值"字段中.

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.

这篇关于POST请求未发送任何请求正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆