如何在node.js(express)中全局设置内容types
我可能是错的,但我无法在任何文档中find它。 我试图设置全球范围内的任何响应的内容types,并像这样做:
// 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);
由于某种原因,这是行不通的。 你知道我在做什么错吗? 分别在每种方法中设置它,但我想在全球范围内…
试试这个 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(); });
发现问题:这个设置必须放在之前:
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)
- 将64Bit Double转换为32Bit浮点Node.Js
- 解决 – 如何使用内容types:应用程序/ JSON,与节点JS上的请求+ restfulapi
- Typescript和Node js得到“不是函数错误”
- streamtypes和合并json对象
- 在全新的快递项目doctype 5`上出现错误,您现在必须使用`doctype html`
- 在Node.js中,读取一个.html文件的目录并在其中search元素属性?
- 与打字稿`toArray`方法不工作的mongodb
- 是否有必要在Node.js中设置一个Content-Type?
- browser.d.ts依赖Edge Web扩展API browser.runtime。* in typescript