2015-02-23 20 views
8

Yanlış olabilirdim, ancak bunu herhangi bir belgede bulamadım. Ben herhangi bir yanıt için global içerik türünü ayarlamak çalışıyorum ve onu sevdin:node.js (express) öğesinde global olarak içerik türü nasıl ayarlanır

// Set content type GLOBALLY for any response. 
    app.use(function (req, res, next) { 
    res.contentType('application/json'); 
    next(); 
    }); 

benim yolları tanımlamadan önce.

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

Bazı nedenlerden dolayı bu çalışmaz. Neyi yanlış yaptığımı biliyor musun?

// this middleware will be executed for every request to the app 
app.use(function (req, res, next) { 
    res.header("Content-Type",'application/json'); 
    next(); 
}); 

cevap

13

Express 4.0 için this deneyin ... çalışıyor ama küresel istediğim bu ayar ÖNCE koymak zorundadır:

app.use(app.router) 

böylece nihai kodudur:

Hata
// 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) 
3

sorunu Bulunan: ayrı ayrı her yöntemde bunu ayarlama,

+0

: 'app.router' itiraz edildi, migratio 4.x için 3.x bakınız Uygulamanızı güncellemeyle ilgili ayrıntılar için n kılavuzu. – rob

İlgili konular