首页 > 解决方案 > 我正在尝试使用 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;

标签: htmljquerynode.jsajaxexpress

解决方案


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.


推荐阅读