express - bodyParser.json()和cors()不能一起工作

时间:2018-02-20 13:44:57

标签: node.js express

我正在使用nodeJs body-parser并从HTML页面向我的nodeJS API发出CORS请求,但是这样做时我收到“意外令牌”的错误。

NodeJS服务器上的错误

    Listening http on port: 3001
SyntaxError: Unexpected token # in JSON at position 0
    at JSON.parse (<anonymous>)
    at createStrictSyntaxError (E:\RnD\src\node_modules\body-parser\lib\types\json.js:157:10)
    at parse (E:\RnD\src\node_modules\body-parser\lib\types\json.js:83:15)
    at E:\RnD\src\node_modules\body-parser\lib\read.js:121:18
    at invokeCallback (E:\RnD\src\node_modules\raw-body\index.js:224:16)
    at done (E:\RnDsrc\node_modules\raw-body\index.js:213:7)
    at IncomingMessage.onEnd (E:\RnD\src\node_modules\raw-body\index.js:273:7)
    at emitNone (events.js:106:13)
    at IncomingMessage.emit (events.js:208:7)
    at endReadableNT (_stream_readable.js:1055:12)

HTML控制台窗口错误

localhost:3001/postCustomer:1 POST http://localhost:3001/postCustomer 400 (Bad Request)

NodeJS API代码

var initHttpServer = () => {
    var app = express();
    var cors = require('cors');

    app.use(cors());
    app.options('*', cors());  // enable pre-flight
    app.use(bodyParser.json());
    app.post('/postCustomer', (req, res) => {
        console.log('customer added: ' );
        res.send();
    });

HTML页面 - API调用

var settings = {
                "async": true,
                "crossDomain": true,
                "url": "http://localhost:3001/postCustomer",
                "method": "POST",
                "headers": {
                    "cache-control": "no-cache",
                    "content-type": "application/json"                    
                },
                "data": {
                        "name": $("#name").val(),
                        "address": $("#address").val(), 
                        "gender": $("#gender").val(),
                        "dob":$("#dob").val()}
                }

                $.ajax(settings).done(function (response) {
                console.log(response);
                });

但是,相同的代码是从 POSTMAN 实用程序成功执行的。

请提出我在这里缺少的内容。

3 个答案:

答案 0 :(得分:3)

我不认为这实际上是CORS的问题,而是使用POST编码。我相信您实际上是在发送网址编码数据。

Post在Postman中运行正常,因为它将数据编码为JSON。

如果我们稍微重写服务器代码:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var cors = require('cors');

var rawBodyHandler = function (req, res, buf, encoding) {
    if (buf && buf.length) {
        req.rawBody = buf.toString(encoding || 'utf8');
        console.log('Raw body: ' + req.rawBody);
    }
}

app.use(cors({ allowedHeaders: 'Content-Type, Cache-Control' }));
app.options('*', cors());  // enable pre-flight

app.use(bodyParser.json({ verify: rawBodyHandler }));

app.post('/postCustomer', (req, res, next) => {
    console.log('customer added: ', JSON.stringify(req.body));
    res.send();

    //next();
});


app.listen(3001);

您会看到AJAX请求实际上是这样的:

Raw body: name=Tommy+D.&address=21+Saltair+Av.%2C+Brentwood%2C+CA&gender=m&dob=1980-21-08

我建议将您的Ajax调用(在客户端上)修改为:

var jsonData = {
                    "name": $("#name").val(),
                    "address": $("#address").val(), 
                    "gender": $("#gender").val(),
                    "dob":$("#dob").val()}
};

var settings = {
                "async": true,
                "crossDomain": true,
                "url": "http://localhost:3001/postCustomer",
                "method": "POST",
                "headers": {
                    "Cache-Control": "no-cache"
                },
                "data":  JSON.stringify(jsonData),
                "contentType": "application/json"
};

$.ajax(settings).done(function (response) {
    console.log(response);
});

答案 1 :(得分:1)

实际上,有两种常见POST请求类型的正文解析器:urlencodedjson

所以,在我们的应用中,我们正在使用:

app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json())

答案 2 :(得分:0)

我遇到了同样的问题

    at JSON.parse (<anonymous>)
    at createStrictSyntaxError (/Users/careaxiom/Documents/WorkEnvironment/monster_pool/mp-api/node_modules/body-parser/lib/types/json.js:158:10)
    at parse (/Users/careaxiom/Documents/WorkEnvironment/monster_pool/mp-api/node_modules/body-parser/lib/types/json.js:83:15)
    at /Users/careaxiom/Documents/WorkEnvironment/monster_pool/mp-api/node_modules/body-parser/lib/read.js:121:18
    at invokeCallback (/Users/careaxiom/Documents/WorkEnvironment/monster_pool/mp-api/node_modules/raw-body/index.js:224:16)
    at done (/Users/careaxiom/Documents/WorkEnvironment/monster_pool/mp-api/node_modules/raw-body/index.js:213:7)
    at IncomingMessage.onEnd (/Users/careaxiom/Documents/WorkEnvironment/monster_pool/mp-api/node_modules/raw-body/index.js:273:7)
    at IncomingMessage.emit (events.js:322:22)
    at endReadableNT (_stream_readable.js:1187:12)
    at processTicksAndRejections (internal/process/task_queues.js:84:21)

这解决了我的问题 app.use(bodyParser.json({strict: false}));