问题描述
我正在使用 NodeJS、Restify 和 PassportJS 为 SPA 构建 REST 后端以进行身份验证.一切正常,除了最后一步,即将客户端从后端/login/facebook/callback 重定向到应用程序的主页.
I'm building a REST backend for an SPA with NodeJS, Restify and PassportJS for authentication. Everything's working except the last step, which is redirecting the client from the backends /login/facebook/callback to the home page of the application.
我在网上搜索并找到了很多关于 ExpressJS 的答案,但对 Node-Restify 还没有任何用处.我已经设法挑选了一些代码片段,这就是我目前正在尝试的:
I've searched online and found lots of answers for ExpressJS but nothing useful for Node-Restify yet. I've managed to pick up a few snippets of code and this is what I'm attempting at the moment:
app.get('/api/v1/login/facebook/cb', passport.authenticate('facebook', { scope: 'email' }), function(req, res) {
req.session.user = req.user._id;
res.header('Location', '/#/home');
res.send();
});
响应已发送,但不包含位置标头,客户端显示白屏.如何使用 Node-Restify API 进行正确的重定向?
The response is sent but the location header is not included and the client is presented with a white screen. How do I do a proper redirect using the Node-Restify API?
推荐答案
Restify 的响应接口 现在有一个 redirect
方法.
Restify's Response interface now has a redirect
method.
在撰写本文时,有一个测试显示如何使用它此处.
As of this writing, there's a test showing how to use it here.
该测试的内容是:
server.get('/1', function (req, res, next) {
res.redirect('https://www.foo.com', next);
});
许多使用 Restify 的人都更熟悉 ExpressJS.重要的是要了解(再次,在撰写本文时)影响 Express 插件移植的三个主要公共 API 差异之一是 Restify 中的 res.redirect
方法要求您通过 next
(或 引发内部错误).我个人将几个模块从 Express 移植到 Restify,最初主要的 API 差异是(在 Restify 中):
Many folks who use Restify are more familiar with ExpressJS. It's important to understand that (again, as of this writing) one of the three main public API differences affecting porting of Express plugins is that the res.redirect
method in Restify requires you to pass next
(or an InternalError is thrown). I've personally ported several modules from Express to Restify and the main API differences at first are (in Restify):
server.use
仅用于路径 &与 HTTP 方法无关的中间件res.redirect
要求您通过next
- 某些成员或请求接口是方法而不是值,例如
req.path
.req.path
是 Restify 中req.getPath
的别名
server.use
is only for path & HTTP-method-agnostic middlewareres.redirect
requires that you passnext
- Some members or the Request interface are methods rather than values, such as
req.path
.req.path
is an alias ofreq.getPath
in Restify
我不是说它们在底层是相似的,但上述三件事是移植 Express 插件的主要障碍.就我在大型企业应用程序和个人项目中使用它的经验而言,Restify 与 Express 相比具有许多优势.
I am NOT saying that under-the-hood they are similar, but that the above three things are the main obstacles to porting over Express plugins. Under-the-hood, Restify has many advantages over Express in my experience using it in both large enterprise applications and personal projects.
这篇关于使用 NodeJS 和 Restify 重定向客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!