node.js - 如何在客户端获取带有 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 作为模板引擎。
解决方案
推荐阅读
- c - C - 读取文件时的无限循环
- react-native - 在 React Native 中卸载应用程序时,我可以捕获事件吗?
- php - 除了@yahoo 帐户之外,所有发件人都收到了 PHP 联系表格
- asp.net - URLEncode 在浏览器 MVC 中不起作用
- php - 尝试更新重复列的行时的 MySQL PHP 语法
- tfs - 您可以将迭代映射到 TFS 板上的列吗?
- swift - 将数据从 NSViewController 传递到 NSSplitViewController 中的另一个 NSViewController?
- java - 使用函数接口抽象公共代码的问题
- javascript - 如果属性值为 false,则保留扩展样式组件的默认值
- ios - OpentTok (iOS) 如何订阅 hasAudio 流的变化