使用 Visual Studio Code、Angular、js 和 ts 有没有办法隐藏 cookie 值,所以你不能在 chrome 检查选项卡中“看到”它, 请参见此处
我是新手,但这是我的代码:在网页上,用户必须先登录。我从我的 userService 发送用户数据:
UserService.js file Front end
import { HttpClient } from '@angular/common/http';
...
login(user: User) {
return this.http.post(`${this.URL}/login`, user);
}
我获取凭据并在后端创建一个像这样的 cookie:
UserControler.js file on the backend
exports.login = async (req, res) => {
//I accsess the data like this
//req.body.email
//req.body.password
// doing some validations, and create an encrypted token
try {
// I catch this on the front end
res.cookie("access-token", token).json({
token: token,
data: user.email,
message: "Successfully Logged In!"
});
} catch(e) {
console.log(e.massage);
}
}
我的登录组件开始了这个故事:
import { UserService } from 'src/app/services/user/user.service';
....
this.userService.login(user).subscribe(
(res: any) => {
this.token = res.token;
this.userFirstName = res.data;
this.successMessage = res['message'];
// setting my new cookie
document.cookie = this.token;
// now every component can check the token with document.cookie
},
(error) => {
console.log(error.error.message);
}
在这个过程中,我可以在我的浏览器中的响应选项卡中看到“cookie”,请参见此处 从这里开始,前端有令牌,理论上它应该在我发出的每个请求中自动发送它,而无需我明确添加它。那是行不通的,我不知道为什么。
我尝试将其设置在标题中,如下所示:
UserService.js Backend
import{ HttpHeaders } from '@angular/common/http';
....
getHeaderOptions(){
const headers= new HttpHeaders()
.set('content-type', 'application/json')
.set('Access-Control-Allow-Origin', '*')
.set('SetCookie', document.cookie); // here is my token in the Set-Cookie header
return {"headers": headers};
}
myFunction(data: string) {
return this.http.post(`${this.URL}/setUserPassword`, data, this.getHeaderOptions());
}
然后在后端我尝试像这样访问该标头:UserControle.js
exports.myFunction = async (req, res) => {
token = "";
if (req.header("Set-Cookie") != undefined) {
token = req.header("Set-Cookie");
retVal = true;
}
}
我得到 req.header("Set-Cookie") 是未定义的,我无法打印 req 对象的值,我得到 [Object object]
所以我需要以下问题的答案:
- 有没有办法从 beckend 隐藏 cookie 中的令牌?
- 如何在我提出的每个请求中发送它?
- 如何在后端访问它?
谢谢你。