res.format 谈判者与 express router get post

res.format negotiator with express router get post

看到 express content negotiator,我想根据收到的内容 header 来处理响应。

例如,这是我的.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'
      })
    }
  })
})

我想做的是,如果请求 header 是标准的 text/html,它应该显示 html 页面和 json 响应,如果请求是 application/json.

问题是,它没有正确拦截 headers。尽管我发出请求(通过 Postman),将 headers 设置为 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
}))

我的猜测是您可能在请求中使用了错误的 header(也许是 Content-Type?)。您需要使用 Accept header。此外,您的文字显示 json/application;那当然应该是application/json

我不使用 Postman,但使用 cURL 效果很好:

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

示例演示使用 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 中测试

curl localhost:3001 -H "content-type: application/json"