javascript - 表单提交不遵循重定向(Node.js)
问题描述
我有一个带有 NodeJS 后端的基本 HTML 站点。
在我的 NodeJS 后端,我有一个基于护照的身份验证流程,可以与 API 端点/api/login一起正常工作以启动身份验证。
在我的 HTML 中,我有一个提交用户电子邮件/密码的基本表单:
<form action="api/login" method="POST" class="cozy">
<input type="text" id="email" name="email" class="form-control form-control-rounded" placeholder="Your registered email" required>
<input type="password" id="password" name="password" class="form-control form-control-rounded" placeholder="Your password" required>
<button type="submit" class="btn btn-accent btn-rounded">Login
<i class="fas fa-long-arrow-alt-right ml-2"></i>
</button>
</form>
如果身份验证成功,我的 NodeJS 端点会返回302状态,标头Location: /app/index.html这是我的应用程序的“仪表板”页面,只能在登录后访问。
app.post('/api/login',
passport.authenticate('local-login', {
successRedirect: '/app/index.html',
failureRedirect: '/login.html'
})
);
app.get('/app/index.html', ensureAuthenticated, function(req, res) {
return res.sendFile(path.join(__dirname + '/private/index.html'));
});
现在,我的浏览器不是重定向到此页面,而是在/app/index.html上执行 XHR 请求,并且我的仪表板页面作为 XHR 请求的响应内容加载,而不是我的用户被重定向到它。
有人知道我做错了什么吗?
解决方案
请.html
从您的路线中删除。在护照身份验证中,您应该将用户重定向到路由而不是某个 .html 文件。在/app/index.html
路线上,您将 index.html 文件作为响应提供。不应该是这样的。而是试试这个。
app.post('/api/login',
passport.authenticate('local-login', {
successRedirect: '/app/index',
failureRedirect: '/login'
})
);
而对于回应
app.get('/app/index', ensureAuthenticated, function(req, res) {
return res.sendFile(path.join(__dirname + '/private/index.html'));
});
希望能帮助到你。
推荐阅读
- javascript - 到达服务时,从 Angular javascript 到 wcf 服务的 Uint8Array 帖子为空
- sql - 聚集索引和非聚集索引与主索引和二级索引
- angular - Angular 框架中的后台活动,类似于 Azure 门户
- flutter - 使用 Provider 类时,此错误不断返回:尝试调用 Provider.of
- c# - 将 MemoryStream 与 .NET 的 System.Speech SpeechRecognitionEngine 类一起使用
- postgresql - 启动postgresql时无法绑定wireguard地址
- bi-publisher - 选择块内的重复变量定义
- amazon-web-services - RDS ScalingConfiguration 参数引发错误
- laravel - Laravel 错误:调用未定义的方法 Illuminate\Support\Facades\Cache::rememberForever()
- c# - 将 WebBrowser 添加到 windows 窗体后 form1.show() 不起作用