簡體   English   中英

如何在node.js(express)中全局設置內容類型

[英]How to set content type globally in node.js (express)

我可能錯了,但我無法在任何文檔中找到它。 我正在嘗試為任何響應設置全局內容類型並執行以下操作:

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

出於某種原因,這不起作用。 你知道我做錯了什么嗎? 在每個方法中單獨設置它,但是我想要全局...

試試對於快遞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();
});

發現問題:此設置必須放在BEFORE之前:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM