无效的JSON GET请求防爆press.jsGET、JSON、js、press

2023-09-10 13:50:11 作者:你 、不在是我的男人

在写一个API,我所遇到的一个非常棘手的错误:当我尝试做一个 res.send(INSERT JSON)与Content-Type头应用程序/ JSON (默认为大多数AJAX),我得到一个无效的JSON 错误。当我设置的内容类型,以其他任何东西(如:文本/纯),我得到了正确的反应,但为了使用一些前端框架,我需要支持应用程序/ JSON 。下面是实际的错误消息:

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:

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)

我的服务器code是如下:

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'});
});

下面是我的邮差设置的画面 - 我用邮差Chrome扩展程序来测试我的API:

Here is an picture of my Postman setup--I am using the Postman Chrome extension to test my API:

推荐答案

我认为,问题是,你要使用Content-Type头在你的服务器响应;不是在你的请求Content-Type头。

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头在你的要求,防爆preSS将读取Content-Type和尝试跨preT所提供的信息作为内容类型,在这种情况下,为JSON。因为这是一个GET请求,因此没有身体,防爆preSS试图跨preT空字符串作为JSON,这是给你的错误。

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.

 
精彩推荐