问题是angular没有向api发送令牌,授权:令牌没有出现在Resquest Header(Nodejs中的api)
继承了发出http请求的组件(get with headers)
ngOnInit() {
this.getPets('/api/animals/all');
}
getPets(URL) {
const userToken = localStorage.getItem('token');
const headers = new HttpHeaders().set('Authorization', userToken);
console.log(headers);
this.httpClient.get(api_url + URL, { headers } ).subscribe(pets => {
this.data = pets;
this.petsHome = this.data.pets;
console.log(this.petsHome);
});
}
继承了定义CORS的api.ts
class Api {
public express: Application;
constructor() {
this.express = express();
this.middleware();
}
middleware(): void {
this.express.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
next();
});
this.express.use(morgan('dev'));
this.express.use(bodyParser.urlencoded( { extended: true } ));
this.express.use(bodyParser.json());
this.express.use(Handlers.errorHandlerApi);
this.router(this.express, Auth);
}
private router(app: Application, auth: any): void {
Routes.initRoutes(app, auth);
}
}
导出默认新的Api()。express;
请求不需要令牌,通常会发生并且响应200 OK。对于不需要令牌的例外登录通常会发生(没有标题)
答案 0 :(得分:0)
试试这个:
res.addHeader("Access-Control-Allow-Headers", "Authorization")
我不确定API是否被称为addHeader
,但你应该明白我的意思。
答案 1 :(得分:0)
我不确定.set
是否有效,另一种方法是在此标题中使用.append
,请尝试以下代码 -
const headers: HttpHeaders = new HttpHeaders()
headers.append('Authorization', userToken);
答案 2 :(得分:0)
我的api正在等待OPTIONS中的令牌
所以......我添加了这段代码
if ('OPTIONS' === req.method) {
res.send(200);
return;
}
这解决了我的问题