OPTIONS 프리 플라이트 요청을 건너 뛰는 방법은 무엇입니까?
저는 PhoneGap 앱을 개발했으며 현재 모바일 웹 사이트로 전환되고 있습니다. 작은 결함 하나 외에 모든 것이 원활하게 작동합니다. POST 요청을 통해 특정 타사 API를 사용하는데, 앱에서는 잘 작동하지만 모바일 웹 사이트 버전에서는 실패합니다.
자세히 살펴보면 AngularJS (실제로 브라우저가 추측)가 먼저 OPTIONS 요청을 보내는 것처럼 보입니다. 오늘 CORS에 대해 많이 배웠지 만 완전히 비활성화하는 방법을 알아낼 수없는 것 같습니다. 나는 해당 API에 대한 액세스 권한이 없지만 (따라서 해당 측면에서 변경할 수 없음) 내가 작업중인 도메인을 Access-Control-Allow-Origin 헤더에 추가했습니다.
이것이 제가 말하는 코드입니다.
var request = {
language: 'fr',
barcodes: [
{
barcode: 'somebarcode',
description: 'Description goes here'
}
]
};
}
var config = {
headers: {
'Cache-Control': 'no-cache',
'Content-Type': 'application/json'
}
};
$http.post('http://somedomain.be/trackinginfo', request, config).success(function(data, status) {
callback(undefined, data);
}).error(function(data, status) {
var err = new Error('Error message');
err.status = status;
callback(err);
});
브라우저 (또는 AngularJS)가 해당 OPTIONS 요청을 보내지 못하게하고 실제 POST 요청으로 건너 뛰려면 어떻게해야합니까? AngularJS 1.2.0을 사용하고 있습니다.
미리 감사드립니다.
프리 플라이트는 Content-Type의 application/json
. 이를 방지하는 가장 간단한 방법은 Content-Type을 text/plain
귀하의 경우 로 설정하는 것 입니다. application/x-www-form-urlencoded
& multipart/form-data
Content-Types도 허용되지만 물론 요청 페이로드의 형식을 적절하게 지정해야합니다.
이 변경 후에도 여전히 프리 플라이트가 표시되는 경우 Angular는 요청에 X- 헤더를 추가 할 수도 있습니다.
또는 트리거 할 헤더 (Authorization, Cache-Control ...)가있을 수 있습니다. 다음을 참조하세요.
Ray가 말했듯이 콘텐츠 헤더를 다음과 같이 수정하여 중지 할 수 있습니다.
$http.defaults.headers.post["Content-Type"] = "text/plain";
예를 들어-
angular.module('myApp').factory('User', ['$resource','$http',
function($resource,$http){
$http.defaults.headers.post["Content-Type"] = "text/plain";
return $resource(API_ENGINE_URL+'user/:userId', {}, {
query: {method:'GET', params:{userId:'users'}, isArray:true},
getLoggedIn:{method:'GET'}
});
}]);
또는 전화로 직접-
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': 'text/plain'
},
data: { test: 'test' }
}
$http(req).then(function(){...}, function(){...});
이것은 비행 전 옵션 요청을 보내지 않습니다.
NOTE: Request should not have any custom header parameter, If request header contains any custom header then browser will make pre-flight request, you cant avoid it.
I think best way is check if request is of type "OPTIONS" return 200 from middle ware. It worked for me.
express.use('*',(req,res,next) =>{
if (req.method == "OPTIONS") {
res.status(200);
res.send();
}else{
next();
}
});
When performing certain types of cross-domain AJAX requests, modern browsers that support CORS will insert an extra "preflight" request to determine whether they have permission to perform the action. From example query:
$http.get( ‘https://example.com/api/v1/users/’ +userId,
{params:{
apiKey:’34d1e55e4b02e56a67b0b66’
}
}
);
As a result of this fragment we can see that the address was sent two requests (OPTIONS and GET). The response from the server includes headers confirming the permissibility the query GET. If your server is not configured to process an OPTIONS request properly, client requests will fail. For example:
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: accept, origin, x-requested-with, content-type
Access-Control-Allow-Methods: DELETE
Access-Control-Allow-Methods: OPTIONS
Access-Control-Allow-Methods: PUT
Access-Control-Allow-Methods: GET
Access-Control-Allow-Methods: POST
Access-Control-Allow-Orgin: *
Access-Control-Max-Age: 172800
Allow: PUT
Allow: OPTIONS
Allow: POST
Allow: DELETE
Allow: GET
Preflight is a web security feature implemented by the browser. For Chrome you can disable all web security by adding the --disable-web-security flag.
For example: "C:\Program Files\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="C:\newChromeSettingsWithoutSecurity" . You can first create a new shortcut of chrome, go to its properties and change the target as above. This should help!
setting the content-type to undefined would make javascript pass the header data As it is , and over writing the default angular $httpProvider header configurations. Angular $http Documentation
$http({url:url,method:"POST", headers:{'Content-Type':undefined}).then(success,failure);
참고URL : https://stackoverflow.com/questions/22968406/how-to-skip-the-options-preflight-request
'Nice programing' 카테고리의 다른 글
Gcc 오류 : gcc : 'cc1'exec 시도 오류 : execvp : 해당 파일 또는 디렉토리가 없습니다. (0) | 2020.10.06 |
---|---|
std :: dynarray 대 std :: vector (0) | 2020.10.05 |
만약 ' (0) | 2020.10.05 |
Java 메서드 선언에서 throw를 사용하는 경우 (0) | 2020.10.05 |
서블릿이 "HTTP 상태 404 요청한 리소스 (/ servlet)를 사용할 수 없습니다."를 반환합니다. (0) | 2020.10.05 |