html - 我正在尝试使用 res.sendFile 在 express 中显示一个 html 文件
问题描述
我正在尝试实现一个工作流程,其中,当用户登录时,用户凭据通过 ajax 发布到快递路线之一,以检查用户是否存在,如果用户存在,快递路线将发回将消息“授权”给 ajax 调用,并调用成功回调,其中另一个 ajax 调用将标头与数据一起发送到快速路由(/重新路由)。这个 express /reroute api 正在尝试 res.redirect 到另一个路由 /homepage。在 /homepage 路由中,我尝试使用 res.sendfile 显示 html 文件,但 res.sendfile 不起作用。
我的登录ajax调用
$(document).on("click", "#login", (e) => {
const email = $('#logemail').val().trim();
const pass = $('#password').val().trim();
$.ajax({
url: "http://localhost:4000/checkuserexists",
type: "POST",
dataType: "JSON",
data: {
email: email,
pass: pass
},
success: function(data, textStatus, request) {
console.log(data)
if (data.message === "authorised") {
const token = request.getResponseHeader('access-token');
localStorage.setItem("access-token", token);
$.ajax({
url: "http://localhost:4000/reroute",
type: "GET",
dataType: "JSON",
beforeSend: function(xhr) {
xhr.setRequestHeader('access-token', token);
},
data: {
redirectTo: 'homepage'
},
success: function(data) {
console.log(data + " from ajax ")
}
})
} else {
$('.alertbox').show();
$('.alertbox').text("User unauthorised");
}
}
})
})
我的快速路线 (/reroute)
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
if (req.header('access-token')) {
const token = req.header('access-token');
const redirectTo = req.query.redirectTo;
if (redirectTo === 'homepage') {
res.setHeader('access-token', token)
res.redirect('/homepage')
}
}
})
module.exports = router;
我的主页路线
const express = require('express');
const path = require('path');
const token_middleware = require('../middlewares/jwtauth');
const router = express.Router();
router.use(express.static(path.join(__dirname, "../public")))
router.get('/', token_middleware, (req, res) => {
if (req.status === "exists") {
res.sendFile(path.join(__dirname, "../public/homepage.html"));
} else {
res.redirect('/');
}
})
module.exports = router;
解决方案
You're requesting the URL with Ajax.
The browser asks for /reroute
and gets a redirect to /homepage
.
It then asks for /homepage
and gets an HTML document.
It passes that HTML document to the JavaScript engine and jQuery tries to parse it as JSON (it ignores the Content-Type
because you said dataType: "JSON"
) and errors.
If you want to do this with Ajax, then don't redirect. Return some JSON that tells your code the login was successful. Then you can navigate with client-side JS and the location
object.
If you want to redirect, then use a regular form submission and not Ajax.
推荐阅读
- python - 用一个简单的数据集理解 LSTM
- wxwidgets - 创建一个 wxPanel 来绘制
- html - 导航栏页面中的 2 侧边栏面板在同一选项卡中
- flutter - 提供集团的正确方法是什么?
- azure - 天蓝色指定要放置任务的输出位置
- sql - 如何在没有子查询的情况下表达这个 SQL 查询
- python - 逗号分隔列表到 Django 模板
- django - /oauth/login/google-oauth2/ 处的 Django Google social-auth ModuleNotFoundError
- c - C如何打印字符串数组中字符串的大小
- ios - SwiftUI 导航栏被切断