2016-05-31 97 views
1

res.format談判代表只見express content negotiator,我想利用處理的響應取決於進來。與快遞路由器獲取後

例如內容標題,這是我的.get()

authRoute.route('/login') 
.get(function(req, res) { 
    res.format({ 
    'text/html': function() { 
     res.render('login', { 
     user: req.user, 
     error: req.flash('error'), 
     loginMessage: req.flash('loginMessage'), 
     active: 'login' 
     }); 
    }, 
    'application/json': function() { 
     res.json({ 
     message: 'This is login page' 
     }) 
    } 
    }) 
}) 

所有我想要做的是,如果該請求頭是標準的text/html,它應該顯示HTML頁中,如果請求的應用程序/ JSON的JSON響應。

問題是,它不能正確攔截標題。雖然我發出請求(經由郵差),設置標頭是application/json,它仍顯示在res.format({..})

上面總是顯示器text/plain代替選配合適條件的第一條件。

任何幫助我做錯了什麼?

authRoute.route('/login') 

.... 

.post(passport.authenticate('local-signup', { 
    successRedirect: '/profile', // redirect to the secure profile section 
    failureRedirect: '/register', // redirect back to the signup page if there is an error 
    failureFlash: true // allow flash messages 
})) 

回答

2

我的猜測是,你可能使用了錯誤的頭中的請求(或許Content-Type?)。您需要使用Accept標題。此外,你的文字說json/application;當然應該是application/json

我不使用郵差,但使用捲曲它工作得很好:

$ curl -H'Accept:application/json' http://localhost:3000 
+0

樣品展示,它是一個錯字,是問題中的'json /應用程序'。謝謝。我正在發送Content-Type,因此爲什麼Express不能提取它。嘗試接受,並工作。 – Rexford

0

使用req.headers

var express = require('express'); 
var app = express(); 

app.get('/', function (req, res) { 
    var contentType = req.headers['content-type']; 
    if(contentType === 'application/json') { 
     return res.json({ 
      message: 'This is login page' 
     }); 
    } 
    res.render('login', { // if not explicitly set, return default render 
     user: req.user, 
     error: req.flash('error'), 
     loginMessage: req.flash('loginMessage'), 
     active: 'login' 
    }); 
}); 

app.listen(3001, function() { 
    console.log('open localhost:3001'); 
}); 

測試在捲曲

curl localhost:3001 -H "content-type: application/json" 
當然
+0

'Content-Type'用於表示請求主體的內容類型,並不意味着用於內容協商。 – robertklep