Answer the question
In order to leave comments, you need to log in
How to add headers to a request in angular2?
Hello to all.
Such a problem, I'm trying to send a request from the service to the backend, I specify the headers
const headerDict = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Test': 'test',
'Authorization':'Bearer '+localStorage.getItem("access_token")
}
let header = new Headers(headerDict);
let data = JSON.stringify({ username: username, password: password })
// this.http.request()
return this.http.post(
this.apihost + 'user/login',
data,
{
'headers': header,
}
) ...
OPTIONS /v2/user/login HTTP/1.1
Host: api.hm.loc
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Access-Control-Request-Method: POST
Origin: ang.hm.loc :4200
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/62.0.3202.75 Chrome/62.0.3202.75 Safari/537.36
Access-Control-Request-Headers: authorization,content- type,test
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7
Answer the question
In order to leave comments, you need to log in
In general, I answer it myself :)
js makes 2 requests, first OPTIONS and only then POST
, so first we send a request with headers, where it is indicated which headers we will accept and what method we expect, and we process the actual POST request
, that is, approximately to Yii we do So
if (\Yii::$app->request->isOptions){
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Method:POST');
header('Access-Control-Allow-Headers:authorization,content-type,test');
die();
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question