无效的JSON GET请求Express.js

时间:2021-04-15 02:33:35

While writing an API, I have come across a very thorny error: when I try to do a res.send(INSERT JSON) with a Content-Type header application/json (a default for most AJAX), I get an invalid json error. When I set the content-type to anything else (eg. text/plain), I get the correct response, but in order to use some front-end frameworks, I need to support application/json. Here is the actual error message:

在编写API时,我遇到了一个非常棘手的错误:当我尝试使用Content-Type头应用程序/ json(大多数AJAX的默认值)执行res.send(INSERT JSON)时,我得到一个无效的json错误。当我将内容类型设置为其他任何内容(例如text / plain)时,我得到了正确的响应,但是为了使用一些前端框架,我需要支持application / json。这是实际的错误消息:

Error: invalid json
    at Object.exports.error (/Users/Brad/node_modules/express/node_modules/connect/lib/utils.js:44:13)
    at IncomingMessage.module.exports (/Users/Brad/node_modules/express/node_modules/connect/lib/middleware/json.js:68:73)
    at IncomingMessage.EventEmitter.emit (events.js:85:17)
    at IncomingMessage._emitEnd (http.js:366:10)
    at HTTPParser.parserOnMessageComplete [as onMessageComplete] (http.js:149:23)
    at Socket.socket.ondata (http.js:1680:22)
    at TCP.onread (net.js:410:27)

My server code is below:

我的服务器代码如下:

app.configure(function () {
  app.use(express.bodyParser());
  app.use(express.cookieParser('SALT'));
  app.use(express.static(__dirname + '/static/'));
  app.use(express.session());
});

app.get('/users', function(req, res) {
  res.send({'test': 'test'});
});

Here is an picture of my Postman setup--I am using the Postman Chrome extension to test my API: 无效的JSON GET请求Express.js

这是我邮差设置的图片 - 我使用Postman Chrome扩展来测试我的API:

1 个解决方案

#1


4  

I believe the problem is that you want to be using Content-Type header in your servers response; not in your request Content-Type header.

我认为问题在于您希望在服务器响应中使用Content-Type标头;不在你的请求内容类型标题。

When you use the Content-Type header in your request, Express will read the Content-Type and attempt to interpret the provided information as that Content-Type, in this case, as JSON. Because this is a GET request and thus has no body, Express is trying to interpret an empty string as JSON, which is giving you the error.

当您在请求中使用Content-Type标头时,Express将读取Content-Type并尝试将提供的信息解释为Content-Type,在本例中为JSON。因为这是一个GET请求,因此没有正文,所以Express试图将空字符串解释为JSON,这会给你错误。

#1


4  

I believe the problem is that you want to be using Content-Type header in your servers response; not in your request Content-Type header.

我认为问题在于您希望在服务器响应中使用Content-Type标头;不在你的请求内容类型标题。

When you use the Content-Type header in your request, Express will read the Content-Type and attempt to interpret the provided information as that Content-Type, in this case, as JSON. Because this is a GET request and thus has no body, Express is trying to interpret an empty string as JSON, which is giving you the error.

当您在请求中使用Content-Type标头时,Express将读取Content-Type并尝试将提供的信息解释为Content-Type,在本例中为JSON。因为这是一个GET请求,因此没有正文,所以Express试图将空字符串解释为JSON,这会给你错误。