node.js - res.format() 在 Express 4.x 中不起作用

标签 node.js express

我是 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/

相关文章:

node.js - "[SyntaxError: Unexpected end of input]"使用 Express for Node.js

javascript - Babel,意外 token (15:33)::

node.js - Socket.io pinginterval 对服务器性能的影响

node.js - 用于传递 JWT 的 httpOnly Cookies 与授权 header

http - 如何在 expressjs 中执行长 HTTP 请求?

express - GraphQl、Sequelize-CLi、模型打包器 - sequelize.import 不是函数

javascript - Mongoose : Best way to get values for an object before save

javascript - Ruby 到 Javascript => 令人头疼的日期计算

Node.js JWT token

node.js - Socket.io 与 AJAX 用例