javascript - 如何在 node.js (express) 中全局设置内容类型

标签 javascript node.js express content-type

我可能错了,但我无法在任何文档中找到它。 我正在尝试为任何响应全局设置内容类型,并且这样做:

    // Set content type GLOBALLY for any response.
  app.use(function (req, res, next) {
    res.contentType('application/json');
    next();
  });

在定义我的路线之前。

 // Users REST methods.
  app.post('/api/v1/login', auth.willAuthenticateLocal, users.login);
  app.get('/api/v1/logout', auth.isAuthenticated, users.logout);
  app.get('/api/v1/users/:username', auth.isAuthenticated, users.get);

由于某种原因,这不起作用。你知道我做错了什么吗?分别在每种方法中设置它,可以工作,但我想要全局...

最佳答案

试试 this对于 Express 4.0:

// this middleware will be executed for every request to the app
app.use(function (req, res, next) {
  res.header("Content-Type",'application/json');
  next();
});

关于javascript - 如何在 node.js (express) 中全局设置内容类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28671174/

相关文章:

node.js - 使用 Express 通过渲染发送多个变量

node.js - 从代码中关闭 Node 实例

javascript - 使用 anchor 标记在 nodeJS 中覆盖方法 GET 到 DELETE

javascript - 为什么我的 Canvas 无法绘制?

javascript - Ionic App 在移动浏览器中运行流畅

javascript - 如果输入是复选框,则捕获正确输入的值

javascript - 如何在我的 Mongoose 模型实例中循环遍历这个数组?

javascript - 使用 javascript 隐藏详细信息 View 字段

javascript - 如果变量是 "something"如何简化这个测试?

node.js - 将文件从一个 Node js服务器发送到另一个