如何在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)
- node.js中的头文件 – 套接口io资源解释为脚本,但是以MIMEtypes传递text / plain:
- 如何在@types上为范围/命名空间包安装TypeScript声明?
- 最稳定的方式将一个32位无符号整数转换为大端字节数组?
- streamtypes和合并json对象
- Node.js – 文件系统获取文件types
- 如何访问模块内的TypeScript定义?
- 解决 – 如何使用内容types:应用程序/ JSON,与节点JS上的请求+ restfulapi
- 将自定义types的数组传递给来自node-pg和SQL注入的postgres函数
- 是否有必要在Node.js中设置一个Content-Type?