我有这个......
import { HttpClient } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { ReqLogin, ResLogin, ResList, ResEmpty} from
'../../interfaces/general';
import { GlobalService} from '../global/global.service';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
...
list(): Observable<ResList> {
const url = this.gs.backendServer + this.gs.backend.endpoints.list;
const httpOptions = {
headers: new HttpHeaders({
'Authorization': this.gs.token
})
};
console.log(httpOptions);
console.log(this.gs.token);
return this.http.get(url, httpOptions)
.map(res => <ResList> res)
.do(dataReceived => console.log(dataReceived));
}
控制台的结果:
HttpHeaders
headers:
Map(1)
size:(...)
:Map
[[Entries]]:Array(1)0:
{"authorization" => Array(1)}
key:
"authorization"
value:["wWTq3NP5LzynzTzYEcHUWgzBC5ioJ1DVW6WDR3QgIDAnc9yrDuVR92iyOQVgooGQ"]
length:1
wWTq3NP5LzynzTzYEcHUWgzBC5ioJ1DVW6WDR3QgIDAnc9yrDuVR92iyOQVgooGQ
因此,授权实际上是按预期进入选项。
但是当我看到请求时......标题不存在......
OPTIONS /list HTTP/1.1
Host: localhost:4600
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: http://localhost:4200
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36
Access-Control-Request-Headers: authorization
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,pt;q=0.8
问题是:出了什么问题?
编辑:代码没错。我只是弄清楚是后端服务器试图处理OPTIONS请求的授权
答案 0 :(得分:2)
在服务器端执行 CORS 时,您需要为&#34;预检&#34;的标题选项添加以下内容:到您现有的** CORS *
if (req.method === "OPTIONS") {
res.sendStatus(200);
} else {
next();
}
我对选项有同样的问题,并且浪费了大约一天的时间,现在我不会忘记它。
答案 1 :(得分:1)
let header = new HttpHeaders();
header = header.append('Authorization', this.gs.token);
const httpOptions ={ headers:header};
您可以尝试更改标题的创建方式
答案 2 :(得分:0)
尝试设置HttpHeaders
而不是传递对象:
list(): Observable<ResList> {
const url = this.gs.backendServer + this.gs.backend.endpoints.list;
let httpOptions = new HttpHeaders()
.set('Authorization', this.gs.token);
return this.http.get(url, { headers: httpOptions })
.map(res => <ResList> res)
.do(dataReceived => console.log(dataReceived));
}