Subtubes
Subtubes

Reputation: 16873

Setting restify default JSON response

I am trying to pipe a file's content using a readStream that writes to restify's response. But I am not able to set the global response Content-Type header

Here is what my code looks like

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

My route action looks like this

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

});

};

For whatever reason my response is not setting the content-type to application/json. I can do it in the route action itself manually using

resp.header('Content-type', 'application/json');

but that would be cumbersome if I had to do it for every route.

Is there something fundamentally wrong with my route action?

Upvotes: 0

Views: 1697

Answers (1)

Aminadav Glickshtein
Aminadav Glickshtein

Reputation: 24590

You don't need to do it for every route. Just add this after listen function:

Try something like that:

server.use(function(req,res,next){
  res.setHeader('content-type','application/json')
 //   OR
  res.setHeaders({'content-type'}:'application/json'})

 next()
})

Upvotes: 2

Related Questions