2016-05-31 101 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