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

Cri*_*riu 12 javascript content-type node.js express

我可能错了,但我无法在任何文档中找到它.我正在尝试为任何响应设置全局内容类型并执行以下操作:

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

在定义我的路线之前.

 // 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);
Run Code Online (Sandbox Code Playgroud)

出于某种原因,这不起作用.你知道我做错了什么吗?在每个方法中单独设置它,但是我想要全局...

A.B*_*A.B 18

试试对于快递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();
});
Run Code Online (Sandbox Code Playgroud)