为什么我的req.body在POST时总是空的?

时间:2017-01-26 09:10:36

标签: javascript ajax node.js express xmlhttprequest

有许多问题是相同的,有答案,但我发现的大多数答案都围绕着我正在使用的身体解析器的使用。我写了很多基本的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));
       }
    };
}

1 个答案:

答案 0 :(得分:0)

如果你设置了

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

然后你需要使用

JSON.stringify(...your object ...) 
正如@JaromandaX所说。 如果你设置

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

然后您需要serialize object object.serialize();。{/ p>