使用 jQuery ajax 方法的简单 expressjs PUT 处理程序

simple expressjs PUT handler with jQuery ajax method

我正在构建一个使用 REST API 与服务器通信的 Web 应用程序,使用 Expres.js 在 Node.js 中构建。问题是我似乎无法读取 PUT 请求中的请求正文。我的客户端代码:

$.ajax({
    url: "/api/model/"+this.database,
    type: "PUT",
    contentType: "application/json",
    data: this.model.exportJSON(),
    success: function(data){
        console.log(data);
    }
});

和服务器端代码(只有重要的部分):

//in the main file
var express = require("express");
var app = express();

var model = require("./apis/model");

app.put("/api/model/:model", model.put);

app.listen(8000);

//in the module
module.exports = {    
    put: function(req, res){
        console.log(req.body);
        res.json({"hello": "world"});
    }
};

模型上的 exportJSON 方法生成一个对象,不是任何空对象,但在服务器端 console.log 我得到 undefined,我做错了什么?

编辑:Chrome 开发人员控制台显示数据发送得很好,所以它必须是服务器端的东西

因为你发送的内容类型是'application/json',你需要添加body-parser中间件:

$ npm install body-parser

然后这样使用:

//in the main file
var express = require("express");
var app = express();
var body = require('body-parser');

app.use(body.json());

app.put("/api/model/:model", function (req, res){
    console.log(req.body);
    res.json({"hello": "world"});
});

app.listen(8000);

然后提出请求

$ curl -i -H "Content-Type: application/json" -X PUT -d '{ "key": "value" }' http://localhost:8000/api/model/foo

这将记录

{ "key" : "value" }

确保在定义路由之前定义 app.use(body) 调用。