Mig*_*use 405 json httpresponse node.js express
因此,可以尝试获取以下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"
}
$
Run Code Online (Sandbox Code Playgroud)
有没有办法在使用node或express的服务器的响应中生成完全相同的主体?显然,可以设置标头并指示响应的内容类型将是"application/json",但是有不同的方式来编写/发送对象.我经常使用的那个是使用以下形式的命令:
response.write(JSON.stringify(anObject));
Run Code Online (Sandbox Code Playgroud)
然而,这有两点可以说是好像是"问题":
另一个想法是使用命令:
response.send(anObject);
Run Code Online (Sandbox Code Playgroud)
这似乎是基于curl的输出发送一个JSON对象,类似于上面的第一个例子.但是,当在终端上再次使用卷曲时,在身体的末端没有新的线条字符.那么,如何使用node或node/express在最后附加一个新行字符来实际记下这样的内容?
bev*_*qua 559
该响应也是一个字符串,如果你想发送响应美化,出于某些尴尬的原因,你可以使用像 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}
Run Code Online (Sandbox Code Playgroud)
美化:
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
// > }
Run Code Online (Sandbox Code Playgroud)
我不确定你为什么要用换行符来终止它,但你可以JSON.stringify(...) + '\n'
做到这一点.
在快递中,您可以通过更改选项来完成此操作.
'json replacer'
JSON替换器回调,默认为null
'json spaces'
用于格式化的JSON响应空间,在开发中默认为2,在生产中默认为0
实际上并不建议设置为40
app.set('json spaces', 40);
Run Code Online (Sandbox Code Playgroud)
然后你可以回答一些json.
res.json({ a: 1 });
Run Code Online (Sandbox Code Playgroud)
它将使用'json spaces
'配置来美化它.
Jam*_*ieL 380
从Express.js 3x开始,响应对象有一个json()方法,它为您正确设置所有头,并以JSON格式返回响应.
例:
res.json({"foo": "bar"});
Run Code Online (Sandbox Code Playgroud)
Con*_*ech 19
如果您尝试发送json文件,则可以使用流
var usersFilePath = path.join(__dirname, 'users.min.json');
apiRouter.get('/users', function(req, res){
var readable = fs.createReadStream(usersFilePath);
readable.pipe(res);
});
Run Code Online (Sandbox Code Playgroud)
vka*_*v15 15
对于大多数情况,该res.json()
功能应该足够了。
app.get('/', (req, res) => res.json({ answer: 42 }));
Run Code Online (Sandbox Code Playgroud)
该res.json()
函数使用将您传递给 JSON 的参数转换为 JSON JSON.stringify()
,并将Content-Type
标头设置为application/json; charset=utf-8
以便 HTTP 客户端知道自动解析响应。
对于问题的标题部分,我要大声疾呼res.type
这里大声喊出:
res.type(\'json\')\n
Run Code Online (Sandbox Code Playgroud)\n\n相当于
\n\nres.setHeader(\'Content-Type\', \'application/json\')\n
Run Code Online (Sandbox Code Playgroud)\n\n来源:快递文档:
\n\n\n\n将 Content-Type HTTP 标头设置为由指定类型的 mime.lookup() 确定的 MIME 类型。如果 type 包含 \xe2\x80\x9c/\xe2\x80\x9d 字符,则它将 Content-Type 设置为 type。
\n
小智 8
您可以为此创建一个帮助程序:创建一个帮助程序功能,以便您可以在应用程序的任何地方使用它
function getStandardResponse(status,message,data){
return {
status: status,
message : message,
data : data
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的主题路线,我试图在其中获取所有主题
router.get('/', async (req, res) => {
const topics = await Topic.find().sort('name');
return res.json(getStandardResponse(true, "", topics));
});
Run Code Online (Sandbox Code Playgroud)
我们得到的回应
{
"status": true,
"message": "",
"data": [
{
"description": "sqswqswqs",
"timestamp": "2019-11-29T12:46:21.633Z",
"_id": "5de1131d8f7be5395080f7b9",
"name": "topics test xqxq",
"thumbnail": "waterfall-or-agile-inforgraphics-thumbnail-1575031579309.jpg",
"category_id": "5de0fe0b4f76c22ebce2b70a",
"__v": 0
},
{
"description": "sqswqswqs",
"timestamp": "2019-11-29T12:50:35.627Z",
"_id": "5de1141bc902041b58377218",
"name": "topics test xqxq",
"thumbnail": "waterfall-or-agile-inforgraphics-thumbnail-1575031835605.jpg",
"category_id": "5de0fe0b4f76c22ebce2b70a",
"__v": 0
},
{
"description": " ",
"timestamp": "2019-11-30T06:51:18.936Z",
"_id": "5de211665c3f2c26c00fe64f",
"name": "topics test xqxq",
"thumbnail": "waterfall-or-agile-inforgraphics-thumbnail-1575096678917.jpg",
"category_id": "5de0fe0b4f76c22ebce2b70a",
"__v": 0
},
{
"description": "null",
"timestamp": "2019-11-30T06:51:41.060Z",
"_id": "5de2117d5c3f2c26c00fe650",
"name": "topics test xqxq",
"thumbnail": "waterfall-or-agile-inforgraphics-thumbnail-1575096701051.jpg",
"category_id": "5de0fe0b4f76c22ebce2b70a",
"__v": 0
},
{
"description": "swqdwqd wwwwdwq",
"timestamp": "2019-11-30T07:05:22.398Z",
"_id": "5de214b2964be62d78358f87",
"name": "topics test xqxq",
"thumbnail": "waterfall-or-agile-inforgraphics-thumbnail-1575097522372.jpg",
"category_id": "5de0fe0b4f76c22ebce2b70a",
"__v": 0
},
{
"description": "swqdwqd wwwwdwq",
"timestamp": "2019-11-30T07:36:48.894Z",
"_id": "5de21c1006f2b81790276f6a",
"name": "topics test xqxq",
"thumbnail": "waterfall-or-agile-inforgraphics-thumbnail-1575099408870.jpg",
"category_id": "5de0fe0b4f76c22ebce2b70a",
"__v": 0
}
]
}
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以使用管道和众多处理器之一对其进行美化。您的应用应始终以尽可能小的负载进行响应。
$ curl -i -X GET http://echo.jsontest.com/key/value/anotherKey/anotherValue | underscore print
Run Code Online (Sandbox Code Playgroud)
https://github.com/ddopson/underscore-cli
您可以使用中间件来设置默认的 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>`);
})
Run Code Online (Sandbox Code Playgroud)
小智 5
如果您使用的是Express,则可以使用以下方法:
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({key:"value"}));
Run Code Online (Sandbox Code Playgroud)
或者只是这个
res.json({key:"value"});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
639243 次 |
最近记录: |