问题描述
在编写API时,我遇到了一个非常棘手的错误:当我尝试使用Content-Type头文件 res.send(INSERT JSON)
code> application / json (大多数AJAX的默认值),我得到一个无效的json
错误。当我将内容类型设置为其他任何东西(例如 text / plain
)时,我得到正确的响应,但为了使用一些前端框架,我需要支持 application / 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)
我的服务器代码如下:
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'});
});
以下是我的邮递员设置的图片 - 我正在使用Postman Chrome扩展程序来测试我的API :
Here is an picture of my Postman setup--I am using the Postman Chrome extension to test my API:
推荐答案
我相信问题是你想在服务器响应中使用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标头时,Express将读取Content-Type,并尝试将提供的信息解释为Content-Type,在这种情况下,作为JSON。因为这是一个GET请求,因此没有任何机构,Express正试图将一个空字符串解释为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.
这篇关于无效的JSON GET Request Express.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!