【问题标题】:Why is my req.body always empty on POST?为什么我的 req.body 在 POST 上总是空的?
【发布时间】:2017-06-11 17:21:23
【问题描述】:

有许多相同的问题,都有答案,但我发现的大多数答案都围绕着我正在使用的 body-parser 的使用。我写了很多基本的 API,从来没有遇到过这个问题。无论我做什么,由于 req.body 为空,属性都没有被保存。

server.js

'use strict'

//basic server setup
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var Routes = require('./routes.js');
var config = require('./config');

// use body parser to parse requests
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static('public'));

//connect to db
var mongoose = require('mongoose');
mongoose.Promise = global.Promise; //temp fix for mongoose promise deprecation warning
mongoose.connect(config.url);

//set port to env or 8080
var port = process.env.PORT || 8080;

//setup routes
var router = express.Router();

//use the imported routes
app.use('/', Routes);

//start the server and log
app.listen(port);
console.log('Server listening on %s', port);  

routes.js

'use strict'

var express = require('express');
var router = express.Router();
var Model = require('./model.js');

var count = 0;

router.use(function(req, res, next) {
    count++;
    console.log('API hit count = %s', count);
    next();
});

// /model post(create new model) get(see all models)
router.route('/model')
.post(function(req,res) {
    var model = new Model();
    model.newKey = req.body.newKey;
    model.newVal = req.body.newVal;

//save the model and checkfor errors
    model.save(function(err) {
        if (err) {
            res.send(err);
        } else {
            res.json({message: "Model created!"});
        }    
    });

})

.get(function(req, res) {
    console.log('made it to GET')
    Model.find(function(err, models) {
        if (err) res.send(err);

        res.json(models);
    })
});

module.exports = router;  

app.js

'use strict';

var post = function() {
    var newKey = $('#postKey').val();
    var newVal = $('#postVal').val();
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("POST", "http://localhost:8080/model", true);

    //Send the proper header information along with the request
    xmlhttp.setRequestHeader("Content-type", "application/json");
    xmlhttp.send({
        newKey: newKey,
        newVal: newVal
    });

    xmlhttp.onreadystatechange = function() {
       if (this.readyState == 4 && this.status == 200) {
            console.log('>>>> ', JSON.parse(this.responseText));
       }
    };
}

var get = function() {
    console.log('Get Button working')
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", "http://localhost:8080/model");
    xmlhttp.send();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            console.log('>>>> ', JSON.parse(this.responseText));
       }
    };
}

【问题讨论】:

  • 我相信你需要.send(JSON.stringify(...your object ...))
  • 如果您设置了xmlhttp.setRequestHeader("Content-type", "application/json");,那么您需要使用@JaromandaX 所说的JSON.stringify(...your object ...)。如果你设置你的xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");,那么你需要serialize你的object
  • 绝对,令人沮丧的太棒了。谢谢你们。

标签: javascript ajax node.js express xmlhttprequest


【解决方案1】:

如果你设置你的

xmlhttp.setRequestHeader("Content-type", "application/json"); 

那么你需要使用

JSON.stringify(...your object ...) 

正如@JaromandaX 所说。 如果你设置你的

xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

那么你需要通过object.serialize();serialize你的object

【讨论】:

  • Ataur,一个后续问题。查看我的 GET 请求。我想传入一个值来搜索数据库。例如,我想发送参数 getKey,这将是通过 Angular 前端输入的键名。我尝试添加 url + "?value=value" 等,但没有运气。
  • 服务器端收到数据了吗?你当时打印了吗?那么完整的网址是什么?
  • 我没有在服务器端获取数据。基本上,如果我尝试跟随这个例子:我什么也得不到。我的网址是localhost:8080/model?newKey=getKey var get = function() { var getKey = $('#getKey').val(); var xmlhttp = 新的 XMLHttpRequest(); xmlhttp.open("GET", "localhost:8080/model?newKey=" + getKey); xmlhttp.setRequestHeader("内容类型", "应用程序/json"); xmlhttp.send(); }
  • 你能查一下var key = req.param('newKey'); console.log(key);
  • 这显示了价值,我根据这个解决了这个问题。不过,我以前从来没有这样做过。我错过了什么吗?
猜你喜欢
  • 2020-07-11
  • 1970-01-01
  • 1970-01-01
  • 2021-12-08
  • 2017-06-12
  • 1970-01-01
  • 1970-01-01
  • 2018-02-03
  • 1970-01-01
相关资源
最近更新 更多