node.js - '授权:承载未定义'
问题描述
当我尝试登录时,授权标头始终未定义。尝试在我的 angular.json 文件中设置 AOT = false 但无济于事。这里有什么问题?
身份验证拦截器
import { HttpHandler, HttpInterceptor, HttpRequest } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { AuthService } from "./auth.service";
@Injectable()
export class AuthInterceptor implements HttpInterceptor{
constructor(private authService: AuthService){}
intercept(req: HttpRequest<any>, next: HttpHandler){
const authToken = this.authService.getToken();
const authRequest = req.clone({
headers: req.headers.set("Authorization", "Bearer " + authToken)
})
return next.handle(authRequest)
}
}
后端的 checkAuth 中间件
const jwt = require('jsonwebtoken');
module.exports = (req, res, next) => {
try{
const token = req.headers.authorization.split(" ")[1]
jwt.verify(token, "asderfghtyu")
next();
}
catch(error) {
res.status(401).json({
message: "Authorization failed macha"
})
}
}
身份验证服务.ts
export class AuthService {
private token: string;
constructor(private http: HttpClient) { }
getToken(){
return this.token;
}
createUser(FullName: string, email: string, role: string, password: string) {
const authData: AuthData = { FullName: FullName, email: email, role: role, password: password }
this.http.post("http://localhost:3300/api/user/signup", authData)
.subscribe(result => {
console.log(result);
})
}
login(email: string, password: string){
this.http.post<{token: string}>("http://localhost:3300/api/user/login", {email: email, password: password})
.subscribe(response=>{
const token = response.token;
this.token = token;
})
}
getToken()
这是存在功能的 auth-service.ts 文件
解决方案
在你的Auth-Interceptor
,替换 -
const authRequest = req.clone({
headers: req.headers.set("Authorization", "Bearer " + authToken)
})
和 -
const authRequest = !authToken ? req : req.clone({
setHeaders: { Authorization: `Bearer ${authToken}` }
});
Authorization
仅当您有令牌时,这才会添加标题。如果authService.getToken()
返回undefined
,则不会Authorization
向请求添加任何标头。
推荐阅读
- reactjs - 是否可以将道具从 React Link 传递到功能组件?
- paypal - 已解决 - 我的 PayPal 支付数据传输 (PDT) 身份令牌在哪里?2020
- progressive-web-apps - 独立的Web应用程序,当应用程序从后台返回时相机是黑色的?
- javascript - 从 API Node JS 获取不正确的数据
- c# - 如何使用 python .Net vs ZeroMQ 或其他方法将 Python 包公开给 C#
- excel - vba如何检查过滤器是否给出结果(可见属性包括标题)
- mysql - docker-compose 的“db”服务中 MYSQL_PASSWORD 的插值格式错误
- android - Android:更换片段时如何停止音乐?
- python - 在 Django 中为我的 PostgreSQL 连接设置纯文本密码是否安全?
- javascript - 如何使用 for 循环进行绑定