因此,人们可以尝试获取以下JSON对象。
$ curl -i -X GET http://echo.jsontest.com/key/value/anotherKey/anotherValue
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Content-Type: application/json; charset=ISO-8859-1
Date: Wed, 30 Oct 2013 22:19:10 GMT
Server: Google Frontend
Cache-Control: private
Alternate-Protocol: 80:quic,80:quic
Transfer-Encoding: chunked
{
"anotherKey": "anotherValue",
"key": "value"
}
$
有没有一种方法可以在使用节点或Express的服务器的响应中产生完全相同的主体?显然,我们可以设置头信息,并指出响应的内容类型是"application/json",但随后有不同的方法来写入/发送对象。我见过的最常用的方式是使用这样的命令。
response.write(JSON.stringify(anObject));
然而,这有两点是可以争论的,好像它们是"问题"。
另一个想法是使用命令。
response.send(anObject);
这似乎是根据curl的输出发送一个JSON对象,与上面的第一个例子类似。然而,当curl再次在终端上使用时,正文的结尾没有新行字符。那么,如何才能真正用node或node/express写下这样的东西,并在结尾处附加一个新的行字符?
响应也是一个字符串,如果你想发送经过预处理的响应,出于一些尴尬的原因,你可以使用类似于JSON.stringify(anObject, null, 3)
的东西。
重要的是,你要把Content-Type
头设置为application/json
。
var http = require('http');
var app = http.createServer(function(req,res){
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ a: 1 }));
});
app.listen(3000);
// > {"a":1}
经过美化。
var http = require('http');
var app = http.createServer(function(req,res){
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ a: 1 }, null, 3));
});
app.listen(3000);
// > {
// > "a": 1
// > }
我不太清楚你为什么要用换行来终止它,但你可以直接做JSON.stringify(...) + 'n'
来实现。
在Express中,你可以通过改变选项来代替来做到这一点。
'json replacer'
JSON replacer回调,默认为空
'json spaces'
用于格式化的JSON响应空间,开发中默认为2,生产中默认为0
实际上不建议设置为40_。
app.set('json spaces', 40);
然后你就可以用一些json来回应。
res.json({ a: 1 });
它将使用'json spaces
'配置来美化它。
你可以使用中间件来设置默认的Content-Type,并为特定的API设置不同的Content-Type。 下面是一个例子。
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
const server = app.listen(port);
server.timeout = 1000 * 60 * 10; // 10 minutes
// Use middleware to set the default Content-Type
app.use(function (req, res, next) {
res.header('Content-Type', 'application/json');
next();
});
app.get('/api/endpoint1', (req, res) => {
res.send(JSON.stringify({value: 1}));
})
app.get('/api/endpoint2', (req, res) => {
// Set Content-Type differently for this particular API
res.set({'Content-Type': 'application/xml'});
res.send(`<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>`);
})
[res.json()
函数][1]应足以应付大多数情况。
app.get('/', (req, res) =>
res.json({ answer:
42 }));
res.json()
函数使用[JSON.stringify()
][2]和[设置Content-Type
头][3]将你传递的参数转换为JSON。
charset=utf-8`所以HTTP客户端知道自动解析响应。
[1]: https://expressjs.com/en/api.html#res.json [2]: http://thecodebarbarian.com/the-80-20-guide-to-json-stringify-in-javascript [3]: https://masteringjs.io/tutorials/express/json
旧版本的Express使用app.use(express.json())
或bodyParser.json()
[阅读更多关于bodyParser中间件][1]。
在最新版本的express中,我们可以简单地使用res.json()
。
const express = require('express'),
port = process.env.port || 3000,
app = express()
app.get('/', (req, res) => res.json({key: "value"}))
app.listen(port, () => console.log(`Server start at ${port}`))
[1]: https://stackoverflow.com/questions/38306569/what-does-body-parser-do-with-express
对于问题的头一半,我'在这里要给res.type
点个赞。
res.type('json')
相当于
res.setHeader('Content-Type', 'application/json')
来源:【快递文档】():。 express docs。
将HTTP头的Content-Type设置为指定类型的mime.lookup()所确定的MIME类型。 如果type包含"/"字符,则将Content-Type设置为type。