簡體   English   中英

使用POST方法時,Node.js req.body為空

[英]Node.js req.body is empty when using POST method

我真的是使用REST和Express的新手,並且一直在關注REST API上的本教程 這是我的app.js代碼:

var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require("mongoose");

var app = express();
var port    = parseInt(process.env.PORT, 10) || 3000;

app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());

Genre = require('./models/genre');

//Connect to mongoose
mongoose.connect('mongodb://localhost/bookstore');

var db = mongoose.connection;

app.listen(port);
console.log('Running on port 3000\n\n');

app.post('/api/genres', function(req, res){
        console.log(req.body);
        var genre = req.body;
        Genre.addGenre(genre, function(err, genre){
            if (err) {
                console.log(err);
                res.send({status: 'something went wrong'});
            }else{
            res.send({status: 'saved'});
            res.json(genre);}
        });
}); 

我在Firefox上使用Rest Easy檢查POST請求。 因為主體為空,所以生成的錯誤是“流派驗證失敗”。 用於此目的的模式在模型中定義為:

var mongoose = require("mongoose");

//Genre Schema
var genreSchema = new mongoose.Schema({

    name: {
        type: String,
        required: true
    },
    create_data:{
        type: Date,
        default: Date.now
    }
});

var Genre = module.exports = mongoose.model('Genre', genreSchema);

// add genre
module.exports.addGenre = function(genre, callback){
    Genre.create(genre, callback);
};

我已經嘗試了其他幾種流行的線程,但是仍然不能解決問題。 我嘗試重新排列模塊導入的順序,並使用“ application / x-www-form-urlencoded”將數據輸入為表單。 任何想法?

編輯 :console.log(req.body)的輸出:

{}

console.log(req)的輸出在jsfiddle.net上的jbkb1yxa上。(由於口碑不好 ,很抱歉,StackOverflow不會讓我嵌入更多鏈接。)REST的截圖: http : //imgur.com/6QmQqRV

在內容類型可用的3個選項的郵遞員中,選擇“ X-www-form-urlencoded”,它應該可以工作。

app.use(bodyParser.urlencoded({
  extended: true
}));

參見https://github.com/expressjs/body-parser

“ body-parser”中間件僅處理JSON和urlencoded數據

在Postman中,要使用原始JSON數據有效負載測試HTTP投遞操作,請選擇raw選項並設置以下標頭參數:

Content-Type: application/json

另外,請確保將用作JSON有效負載中的鍵/值的所有字符串都用雙引號引起來。

body-parser包將很好地解析多行原始JSON負載。

{
    "foo": "bar"
}

您需要在REST Easy端的data部分中輸入正確的MIME類型:

application/json

可能是因為您對數據庫的調用找不到您要查找的內容。 當我剛開始學習貓鼬時,我的一個巨大痛苦點是我錯誤地認為將空洞的回答視為err但事實並非如此。

如果將console.log(genre)放在res.sendres.json語句之上,會res.json什么?

另外,我只是想知道,為什么要使用res.send后跟res.json

好。 所以我想這可能是擴展問題。 我使用相同的代碼在chrome中使用POSTMAN發送POST請求,現在工作正常。 甚至甚至Postman都無法正常工作,但是在將chrome配置為不使用代理服務器后,它就可以正常工作。

謝謝大家的幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM