首页 > 解决方案 > 如何在客户端获取带有 Express/NodeJS 后端的 res.header() 并发回?

问题描述

我创建了一个 API,我想将令牌发送到前端,然后将其存储在 localStorage 上以授权最受保护的路由,但是我在客户端获取 res.header() 时遇到了一些问题。

我的目标是:将其发送到前端,将其保存在 localStorage 上,然后在用户尝试访问某些路由时发回,这样我就可以使用它来进行授权。

这是我的代码:

用户控制器.js

login: async (req, res)=>{
    
    //check if the user exists on database
    const userInput = req.body;
    const userExists = await userModel.findOne({email: userInput.email});
    if(!userExists) return res.status(401).send('Email or password are incorrets.');

    //compares the input password with the encripted password in database
    const matchPassword = bcrypt.compareSync(userInput.password, userExists.password);
    if(!matchPassword) return res.status(401).send('Email or password are incorrets.');
    const makedToken = jwt.sign({email: userInput.email, vip: userExists.vip}, process.env.USER_SECRET);

    // here is the header that I want to send to client-side
    res.header('authorization-token', makedToken);
    res.render("mainPage.ejs");

}

所以,我在前端尝试了 fetch() 。它可以发送并且我也可以看到响应,但是我无法访问包含我想要的令牌的标头响应。我只能看到 json 响应。

任何人都知道我该怎么做?我使用 ejs 作为模板引擎。

标签: node.jsexpressgetheaderclient-side

解决方案


推荐阅读