在nodejs中的res.end()之后redirect

我正在使用jsonwebtoken来validation用户。 我的计划是将标记保存在标题处,然后在发出任何请求之前获取标题值。 是的,我确实保存在login头成功的值,但它应该redirect到其他页面像任何其他应用程序做的。 我尝试redirect或呈现其他页面,并得到错误

发送后无法设置标题。

apiRoutes.post('/authenticate', function(req, res) { User.findOne({ name: req.body.name }, function(err, user) { if (err) throw err; if (!user) { res.json({ success: false, message: 'Authentication failed. User not found.' }); } else if (user) { if (user.password != req.body.password) { res.json({ success: false, message: 'Authentication failed. Wrong password.' }); } else { var token = jwt.sign(user, app.get('superSecret'), { expiresInMinutes: 60 // expires in 4 hours }); var body = "hello world"; res.writeHead(200, { "Content-Length": body.length, "Content-Type": "text/plain", "x-access-token":token }); res.end(); console.log('token saved '+res.getHeader('x-access-token')); } } }); }); 

这里是完整的项目项目

这没有意义。 一个http响应只有一个状态码。 这是您的JSON数据与地位标题设置为200状态或302状态。 它根本不可能是两个。 选一个。

如果你愿意,你可以把一个位置redirect到你的JSON响应,并让客户端在处理JSON响应后手动进入该redirect位置。

如果需要,你可以在200响应中放置一个位置标题,但是浏览器不会自动执行。

另外,如果这个请求是来自浏览器的Ajax调用,那么浏览器不会因为您发送redirect响应而改变页面。 接收到Ajax调用的代码将不得不更改页面本身。

此外, res.json(...)立即发送响应,因此发送后不能再写入更多内容。

试试这个,它适用于我…

 res.writeHead(200, { "Content-Length": body.length, "Content-Type": "text/plain", "x-access-token":token, "Location": "http://www.google.com" })