我正在尝试使用写入restify响应的readStream来管道文件的内容。但我无法设置全局响应Content-Type标头
这是我的代码看起来像
let restify = require('restify');
let router = require('./routes');
let server = restify.createServer({
formatters: null,
log: null,
spdy: null,
version: '0.0.1',
handleUpgrades: false
});
server.listen(8080, function() {
console.log('%s listening at %s', server.name, server.url);
});
//I think this is suppose to set the response header across the app but it is not
restify.defaultResponseHeaders = function(data) {
this.header('Content-Type', 'application/json');
};
server.use(restify.acceptParser(server.acceptable));
server.use(restify.authorizationParser());
server.use(restify.CORS());
server.use(restify.dateParser());
server.use(restify.queryParser());
server.use(restify.gzipResponse());
server.use(restify.bodyParser());
server.use(restify.requestLogger());
//server.use(restify.throttle());
server.use(restify.conditionalRequest());
server.use(restify.fullResponse());
server.use(restify.bodyParser());
//router
router(server);
我的路线动作如下所示
let fs = require('fs');
module.exports = function ecmaRoutes(server) {
let PATH = '/sample/';
server.get(function sampleV1(req, resp) {
let path = 'sample.json';
let rStream = fs.createReadStream(path);
rStream.pipe(resp);
});
};
无论出于何种原因,我的回复都没有将内容类型设置为application/json
。我可以使用
resp.header('Content-type', 'application/json');
但如果我必须为每条路线做这件事,那就太麻烦了。
我的路线行动是否存在根本性的错误?
答案 0 :(得分:2)
您不需要为每条路线都这样做。只需在listen
函数后添加:
尝试类似的东西:
server.use(function(req,res,next){
res.setHeader('content-type','application/json')
// OR
res.setHeaders({'content-type'}:'application/json'})
next()
})