我一直试图解决这个问题,但我无法找到相关的文档或示例。
我向我的测试轨道服务器发送请求,而且回复只有2个标头,而使用REST测试工具(例如邮递员),我得到了所有预期的标题。
这就是我调用服务器的方式:
// Base Class
@Injectable()
export class BaseResource {
constructor(
protected http : HttpClient,
protected authTokenService : AuthTokenService,
protected storage : LocalStorageService
){}
public getHost() : string {
let server = this.storage.get<string>("server");
if (server.lastIndexOf("http", 0) !== 0) {
server = "https://" + server + ".example.com/v2";
}
return server;
}
public getHostUrl(resource: string) : string {
return this.getHost() + "/" + resource;
}
public performGet(url : string) : Observable<any> {
return this.http.get(this.getHostUrl(url), this.getHttpOptions());
}
public performPost(url : string, body : {}) : Observable<any> {
return this.http.post(this.getHost(url), body, this.getHttpOptions());
}
protected getHttpOptions() : {} {
const authToken = this.authTokenService.getAuthHeaderValue();
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': authToken
}),
observe: 'response'
};
return httpOptions;
}
}
这是一个精简的专业子实例
@Injectable()
export class EntryResource extends BaseResource {
get(): Observable<any> {
return this.performGet("entries");
}
}
这就是一切都被称为
@Injectable()
export class EntryService {
constructor(private resource: EntryResource) { }
getEntries() : Promise<Entry[]> {
return new Promise((resolve, reject) => {
this.resource.get().subscribe(
data => {
console.log(data.headers.keys());
resolve(data.body as Entry[]);
},
error => {
reject(error);
}
);
});
}
}
最后,将以下标题打印到控制台:
(2) ["content-type", "cache-control"]
以下是邮递员显示的标题:
Cache-Control →max-age=0, private, must-revalidate
Connection →Keep-Alive
Content-Length →3416
Content-Type →application/json; charset=utf-8
Date →Fri, 23 Mar 2018 19:38:44 GMT
Etag →W/"914d1759e9dcdbdb05450efa629a0b03"
Server →WEBrick/1.3.1 (Ruby/2.3.1/2016-04-26)
Vary →Origin
X-Content-Type-Options →nosniff
X-Frame-Options →SAMEORIGIN
X-Pagination →{"total":123,"total_pages":9,"current_page":1,"first_page":true,"last_page":false,"next_page":2,"out_of_bounds":false,"page_size":15}
X-Request-Id →20cccf61-4816-4e61-a7a7-c71adeb604d7
X-Runtime →0.922868
X-Xss-Protection →1; mode=block
为什么标题会被棱角分开?
答案 0 :(得分:2)
尝试设置Access-Control-Allow-Headers
标头服务器端以公开这些标头
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers
Access-Control-Allow-Headers: X-Frame-Options, X-header-2
这是必需的,因为浏览器出于安全原因实施CORS,而测试工具(Postman,其他休息客户端)和非浏览器应用程序则不然。我不知道android,但我的猜测是,如果使用webviews,你需要CORS