首页 > 解决方案 > 表单提交不遵循重定向(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 请求的响应内容加载,而不是我的用户被重定向到它。

有人知道我做错了什么吗?

标签: javascripthtmlnode.jsformspassport.js

解决方案


.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'));
});

希望能帮助到你。


推荐阅读