因此,可以尝试获取以下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"
}
$
有没有办法在使用node或express的服务器的响应中生成完全相同的主体?显然,可以设置标头并指示响应的内容类型将是“application / json”,但是有不同的方式来编写/发送对象。我经常使用的那个是使用以下形式的命令:
response.write(JSON.stringify(anObject));
然而,这有两点可以说是好像是“问题”:
另一个想法是使用命令:
response.send(anObject);
这似乎是基于curl的输出发送一个JSON对象,类似于上面的第一个例子。但是,当在终端上再次使用卷曲时,在身体的末端没有新的线条字符。那么,如何使用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'
来实现它。
快递你可以通过changing the options instead来做到这一点。
'json replacer'
JSON替换器回调,默认为null用于格式化的
'json spaces'
JSON响应空间,在开发中默认为2,在生产中默认为0
实际上并不建议设置为40
app.set('json spaces', 40);
然后你可以回答一些json。
res.json({ a: 1 });
它将使用'json spaces
'配置来美化它。
从Express.js 3x开始,响应对象有一个json()方法,它为您正确设置所有头,并以JSON格式返回响应。
例:
res.json({"foo": "bar"});
如果您尝试发送json文件,则可以使用流
var usersFilePath = path.join(__dirname, 'users.min.json');
apiRouter.get('/users', function(req, res){
var readable = fs.createReadStream(usersFilePath);
readable.pipe(res);
});
你可以使用管道和许多处理器中的一个来美化它。您的应用应始终以尽可能小的负载响应。
$ curl -i -X GET http://echo.jsontest.com/key/value/anotherKey/anotherValue | underscore print
如果你使用Express你可以使用这个:
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({key:"value"}));
或者就是这个
res.json({key:"value"});
您可以使用中间件来设置默认的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>`);
})
较早版本的Express使用app.use(express.json())
或bodyParser.json()
read more about bodyParser middleware
在最新版本的快递我们可以简单地使用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}`))
对于标题的一半问题,我要在这里向res.type
大喊:
res.type('json')
相当于
res.setHeader('Content-Type', 'application/json')
来源:express docs:
将Content-Type HTTP标头设置为由mime.lookup()为指定类型确定的MIME类型。如果type包含“/”字符,则它将Content-Type设置为type。