14

我正在使用以下数据在 Node 上访问 Web 服务,

我的请求数据是:

{
"first_name":"surinder",,
"last_name":"rawat",
"email":"surinder.rawat@testcompany.com",
"phone":"1234567890",
"password":"surinder",
"user_type":"H",
"device_type":"A"
}

并得到以下错误:

Connect
400 SyntaxError: Unexpected token ,
   at Object.parse (native)
   at parse (/home/surinder/workspace/HappyHakka/node_modules/body-parser/lib/typs
   /json.js:76:17)
   at /home/surinder/workspace/HappyHakka/node_modules/body-parser/lib/read.js:98:18
   at IncomingMessage.onEnd (/home/surinder/workspace/HappyHakka/node_modules/body-parser
   /node_modules/raw-body/index.js:136:7)
   at IncomingMessage.g (events.js:180:16)
   at IncomingMessage.emit (events.js:92:17)
   at _stream_readable.js:943:16
   at process._tickCallback (node.js:419:13)

我故意使用双逗号来得到这个错误。我想知道如何处理此错误并以正确的格式向用户显示错误

谢谢

4

2 回答 2

10

文档-

您最后定义错误处理中间件,在其他app.use()和路由调用之后;例如:

var bodyParser = require('body-parser');
var methodOverride = require('method-override');

app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(function(err, req, res, next) {

  // error handling logic
  console.error(err.stack);
  res.status(500).send('Something broke!');

});
于 2016-09-14T12:03:43.037 回答
0

它与body-parserraw-body包有关,如果您想以更强大的方式解决此问题并处理从 body parser 抛出的所有错误,请使用此中间件

https://github.com/ntedgi/express-body-parser-error-handler

$ npm i express-body-parser-error-handler

例如,它将处理从 body-parser 抛出的所有常见错误

'encoding.unsupported'、'entity.parse.failed'、'entity.verify.failed'、'request.aborted'、'request.size.invalid'、'stream.encoding.set'、'parameters.too.many '、'charset.unsupported'、'encoding.unsupported'、'entity.too.large'

用法示例:

const bodyParserErrorHandler = require('express-body-parser-error-handler')
const { urlencoded, json } = require('body-parser')
const express = require('express')
const app = express();
router.route('/').get(function (req, res) {
    return res.json({message:""});
});

// body parser initilization
app.use(urlencoded({extended: false, limit: defaultLimitSize}));
app.use('/', json({limit: '250'}));

// body parser error handler
app.use(bodyParserErrorHandler());
app.use(router);
...
于 2021-12-25T07:29:15.880 回答