Angular 5의 헤더에 CORS 요청을 추가하는 방법
헤더에 CORS를 추가했지만 요청에 CORS 문제가 계속 발생합니다. 헤더에서 CORS 및 기타 요청을 추가하고 처리하는 올바른 방법은 무엇입니까?
다음은 서비스 파일 코드입니다.
import { HttpClient, HttpHeaders, HttpClientModule } from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({
'Access-Control-Allow-Origin':'*',
'Authorization':'authkey',
'userid':'1'
})
};
public baseurl = 'http://localhost/XXXXXX';
userAPI(data): Observable<any> {
return this.http.post(this.baseurl, data, httpOptions)
.pipe(
tap((result) => console.log('result-->',result)),
catchError(this.handleError('error', []))
);
}
오류:
실행 전 요청에 대한 응답이 액세스 제어 검사를 통과하지 못함 : 요청 된 리소스에 'Access-Control-Allow-Origin'헤더가 없습니다. 따라서 원본 ' http : // localhost : 4200 '은 액세스가 허용되지 않습니다.
실패 : (알 수없는 URL)에 대한 HTTP 실패 응답 : 0 알 수없는 오류
내 서버 측 코드에서 인덱스 파일에 CORS를 추가했습니다.
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
CORS (Cross-Origin Resource Sharing)는 서버가 "귀하가 다른 출처에서 왔음에도 불구하고 귀하의 요청을 수락하겠습니다"라고 말하는 방법입니다. 이를 위해서는 서버의 협력이 필요합니다. 따라서 서버를 수정할 수없는 경우 (예 : 외부 API를 사용하는 경우)이 방법은 작동하지 않습니다.
Access-Control-Allow-Origin : * 헤더를 추가하도록 서버를 수정하여 어디서나 교차 출처 요청을 활성화합니다 (또는 * 대신 도메인 지정).
내 경험상 플러그인은 HTTP에서 작동했지만 최신 httpClient에서는 작동하지 않았습니다. 또한 서버에서 CORS 응답 헤더를 구성하는 것은 실제로 옵션이 아닙니다. 그래서 proxy.conf.json
프록시 서버 역할을하는 파일을 만들었습니다 .
여기에서 이에 대해 자세히 알아보십시오 .
proxy.conf.json
파일:
{
"/posts": {
"target": "https://example.com",
"secure": true,
"pathRewrite": {
"^/posts": ""
},
"changeOrigin": true
}
}
동일한 디렉토리 의 proxy.conf.json
파일 바로 옆에 파일을 배치 했습니다 package.json
.
그런 다음 package.json 파일에서 시작 명령을 수정했습니다.
"start": "ng serve --proxy-config proxy.conf.json"
내 앱 구성 요소의 HTTP 호출 :
return this._http.get('/posts/pictures?method=GetPictures')
.subscribe((returnedStuff) => {
console.log(returnedStuff);
});
마지막으로 앱을 실행하려면 npm start
또는ng serve --proxy-config proxy.conf.json
NG5의 HttpClient에 대한 헤더를 다음과 같이 만드십시오.
let httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'apikey': this.apikey,
'appkey': this.appkey,
}),
params: new HttpParams().set('program_id', this.program_id)
};
localhost URL로 API 호출을 할 수 있습니다.
- 헤더에있는 매개 변수를 잊지 마십시오 : params : new HttpParams (). set ( 'program_id', this.program_id)
Angular 6에서 httpClient를 사용한 POST도 OPTIONS 요청을 수행했습니다.
헤더 일반 :
요청 URL : https : //hp-probook/perl-bin/muziek.pl/=/postData 요청 방법 : 옵션 상태 코드 : 200 OK 원격 주소 : 127.0.0.1 : 443 리퍼러 정책 : 다운 그레이드시 리퍼러 없음
내 Perl REST 서버는 반환 코드 200으로 OPTIONS 요청을 구현합니다.
다음 POST 요청 헤더 :
동의하기:*/* Accept-Encoding : gzip, deflate, br Accept-Language : nl-NL, nl; q = 0.8, en-US; q = 0.6, en; q = 0.4 액세스 제어 요청 헤더 : 콘텐츠 유형 액세스 제어 요청 방법 : POST 연결 : 연결 유지 호스트 : hp-probook 출처 : http : // localhost : 4200 참조 자 : http : // localhost : 4200 / User-Agent : Mozilla / 5.0 (X11; Linux x86_64) AppleWebKit / 537.36 (Gecko와 같은 KHTML) Chrome / 59.0.3071.109 Safari / 537.36
Access-Control-Request-Headers : content-type에주의하십시오.
따라서 내 백엔드 펄 스크립트는 다음 헤더를 사용합니다.
- "Access-Control-Allow-Origin"=> '*', - "Access-Control-Allow-Methods"=> 'GET, POST, PATCH, DELETE, PUT, OPTIONS', - "Access-Control-Allow-Headers"=> 'Origin, Content-Type, X-Auth-Token, content-type',
이 설정으로 GET 및 POST가 작동했습니다!
각도 cors에서 requestoptions를 가져 오십시오
import {RequestOptions, Request, Headers } from '@angular/http';
and add request options in your code like given below
let requestOptions = new RequestOptions({ headers:null, withCredentials:
true });
send request option in your api request
code snippet below-
let requestOptions = new RequestOptions({ headers:null,
withCredentials: true });
return this.http.get(this.config.baseUrl +
this.config.getDropDownListForProject, requestOptions)
.map(res =>
{
if(res != null)
{
return res.json();
//return true;
}
})
.catch(this.handleError);
}
and add CORS in your backend PHP code where all api request will land first.
try this and let me know if it is working or not i had a same issue i was adding CORS from angular5 that was not working then i added CORS to backend and it worked for me
You can also try the fetch
function and the no-cors
mode. I sometimes find it easier to configure it than Angular's built-in http module. You can right-click requests in the Chrome Dev tools network tab and copy them in the fetch syntax, which is great.
import { from } from 'rxjs';
// ...
result = from( // wrap the fetch in a from if you need an rxjs Observable
fetch(
this.baseurl,
{
body: JSON.stringify(data)
headers: {
'Content-Type': 'application/json',
},
method: 'POST',
mode: 'no-cors'
}
)
);
The following worked for me after hours of trying
$http.post("http://localhost:8080/yourresource", parameter, {headers:
{'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' } }).
However following code did not work, I am unclear as to why, hopefully someone can improve this answer.
$http({ method: 'POST', url: "http://localhost:8080/yourresource",
parameter,
headers: {'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST'}
})
Using jsonp...
in the application calling the API:
import { HttpClient } from "@angular/common/http";
this.httpClient.jsonp("http://127.0.0.1:3001/scicat/Publication", "callback")
...
In the callee:
import { Request, Response } from "express";
// is commonly cross a cross origin request
export let getPublication = (req: Request, res: Response) => {
logger.debug("Get publications request.");
const dao = MongoConnector.getInstance();
dao
.getPublication(req.query)
.then(response => {
Response.jsonp(response);
})
.catch(oaiError => {
Response.status(500);
Response.jsonp(oaiError);
});
};
참고URL : https://stackoverflow.com/questions/47345282/how-to-add-cors-request-in-header-in-angular-5
'IT TIP' 카테고리의 다른 글
pip를 사용하여 사용 가능한 Python 패키지를 검색하려면 어떻게해야합니까? (0) | 2020.12.08 |
---|---|
: hover에 반대되는 CSS 의사 클래스가 있습니까? (0) | 2020.12.08 |
NoRouteToHostException을 피하는 방법? (0) | 2020.12.08 |
Javascript / jQuery를 사용하여 외부 스타일 시트에서 CSS 값 가져 오기 (0) | 2020.12.08 |
UIEdgeInsetsMake는 어떻게 작동합니까? (0) | 2020.12.08 |