为什么我的req.body在POST上总是为空? [英] Why is my req.body always empty on POST?

查看:107
本文介绍了为什么我的req.body在POST上总是为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

There are many questions that are the same, with answers, but most answers I have found revolve around the use of body-parser, which I am using. I have written many basic APIs and have never had this issue. No matter what I do, the attributes are not being saved due to the empty 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));
       }
    };
}

推荐答案

如果您设置

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

然后您需要使用

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

如@JaromandaX所说.如果您设置

as @JaromandaX said. if you set your

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

然后您需要通过 object.serialize(); 序列化您的 object .

then you need to serialize your object by object.serialize();.

这篇关于为什么我的req.body在POST上总是为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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