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

13

我可能错了,但是我找不到任何文件中有这个的说明。 我正在尝试全局设置任何响应的内容类型,并像这样做:


我可能不正确,但我无法在任何文档中找到这个信息。我正在尝试将任何响应的内容类型全局设置,并已这样完成:
    // 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);

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

2个回答

20

对于 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();
});

4
发现问题:此设置必须放在以下位置之前:
app.use(app.router)

所以最终的代码是:

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

// routes should be at the last
app.use(app.router)

错误:'app.router'已弃用,请参阅3.x至4.x迁移指南,了解如何更新您的应用程序。 - rob

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接