我是 Node.js 新手,开始学习 Express。 我尝试将内容类型设置为文本/纯文本,它应该响应“嘿,我是文本” 但实际上它响应“嘿,我是 html”,甚至状态代码:304,未修改。
谁能帮忙解释一下原因吗?
router.get('/index1.html', function (req, res, next) {
res.set('Content-Type', 'text/plain');
res.format({
'text/plain': function () {
res.send('hey, i am text');
},
'text/html': function () {
res.send('<p>hey, i am html</p>');
},
'application/json': function () {
res.send({ message: 'hey, i am json' });
},
'default': function () {
// log the request and respond with 406
res.status(406).send('Not Acceptable');
}
});
next();
});
最佳答案
据快报document , res.format()
的意思是:
Performs content-negotiation on the Accept HTTP header on the request object, when present...select a handler for the request, based on the acceptable types ordered by their quality values.
即res.format()
会检查Accept
HTTP请求头,并根据Accept
值调用相应的处理程序。
在您的情况下,当请求发送到 /index1.html
时,浏览器将自动将 Accept
header 设置为 Accept:text/html,application/xhtml+xml...
-- text/html
将是第一个。然后,当执行 res.format()
时,它将接受 Accept
as text/html
并返回 hey, i am html
.
对于 res.set('Content-Type', 'text/plain');
,请注意您刚刚在响应中设置了 Content-Type
header ,它具有与res.format()
无关。
关于node.js - res.format() 在 Express 4.x 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45983014/