【问题标题】:How to set content type globally in node.js (express)如何在 node.js (express) 中全局设置内容类型
【发布时间】:2015-04-24 14:56:35
【问题描述】:

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

    // 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);

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

【问题讨论】:

    标签: javascript node.js express content-type


    【解决方案1】:

    在 Express 4.0 中尝试 this

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

    【讨论】:

      【解决方案2】:

      发现问题:此设置必须放在之前:

      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 迁移指南。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-12
      • 1970-01-01
      • 2016-09-28
      • 2014-09-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多