Node.js (Express API): req.body.myobject未定义,无法工作

Node.js (Express API): req.body.myobject is undefined and not working

本文关键字:未定义 myobject 工作 body req js Express API Node      更新时间:2023-09-26

我有我的服务器端在NodeJS (ExpressJS)它实现了一个POST方法,应该得到我从客户端发送的对象和做的事情:

router.route('/email')
// create a mail (accessed at POST http://localhost:8080/api/email)
.post(function(req, res) {
    var email = req.body.email;
    // do things with email...
    // but it's complaining because it says it's 'undefined'
});

req.body.email应该是JSON对象,结构如下:

{"destinatary": "my@example.com", "subject": "mysubject", "message": "mymessage"}

我已经实现了一个非常简单的web客户端使用jQuery来测试我的API,其中AJAX调用它是这样做的:

function sendEmail(email) {
  $.post(MYAPP.service_uri+"/email",
    email,
    function(data, status){
        alert("Data: " + data + "'nStatus: " + status);
    });
}

在客户端,email是一个对象,所以它不是undefined…但是我每次都在服务器端得到以下错误:

TypeError: Cannot read property 'destinatary' of undefined

因为您没有发送任何名为email的内容-您附加了一个变量名为email的对象

修复AJAX调用,你可以这样做:

$.post(MYAPP.service_uri+"/email",
    {email: email}, //OBJECT, KEYVAL PAIR
    function(data, status){
        alert("Data: " + data + "'nStatus: " + status);
    }
);

原始代码中的对象将存储在纯req.body中-而不是req.body.email

如果您不想修复AJAX调用,您可以修复服务器:

router.route('/email')
// create a mail (accessed at POST http://localhost:8080/api/email)
.post(function(req, res) {
    var email = req.body;
});