Cross-Origin Resource Sharing(CORS) 사후 요청을 처리하는 방법
로컬 LAN(머신 A)에 웹 서버가 2개 있는 머신이 있습니다.첫 번째는 XBMC(포트 8080)에 내장된 것으로, 라이브러리를 표시합니다.두 번째 서버는 CherryPy py python 스크립트(포트 8081)로, 온 디맨드로 파일 변환을 트리거하기 위해 사용하고 있습니다.파일 변환은 XBMC 서버에서 제공되는 페이지에서 AJAX POST 요청에 의해 트리거됩니다.
- 라이브러리를 표시하는 Goto http://machineA:8080
- 라이브러리가 표시됩니다.
- 사용자는 다음 명령을 발행하는 '변환' 링크를 클릭합니다.
jQuery Ajax 요청
$.post('http://machineA:8081', {file_url: 'asfd'}, function(d){console.log(d)})
- 브라우저는 다음 헤더의 HTTP OPTIONS 요구를 발행합니다.
요청 헤더 - OPTIONS
Host: machineA:8081
User-Agent: ... Firefox/4.01
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Origin: http://machineA:8080
Access-Control-Request-Method: POST
Access-Control-Request-Headers: x-requested-with
- 서버는 다음과 같이 응답합니다.
응답 헤더 - OPTIONS(상태 = 200 OK)
Content-Length: 0
Access-Control-Allow-Headers: *
Access-Control-Max-Age: 1728000
Server: CherryPy/3.2.0
Date: Thu, 21 Apr 2011 22:40:29 GMT
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, GET, OPTIONS
Content-Type: text/html;charset=ISO-8859-1
- 그 후, 대화가 정지합니다.이론적으로 서버가 올바른(?) CORS 헤더로 응답하면 브라우저는 POST 요구를 발행합니다(Access-Control-Allow-Origin: *).
트러블 슈팅을 위해 http://jquery.com에서 동일한 $.post 명령어를 발행했습니다.jquery.com에서 투고 요청이 이루어지면 POST에 이어 OPTIONS 요청이 발송됩니다.이 트랜잭션의 헤더는 다음과 같습니다.
요청 헤더 - OPTIONS
Host: machineA:8081
User-Agent: ... Firefox/4.01
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Origin: http://jquery.com
Access-Control-Request-Method: POST
응답 헤더 - OPTIONS(상태 = 200 OK)
Content-Length: 0
Access-Control-Allow-Headers: *
Access-Control-Max-Age: 1728000
Server: CherryPy/3.2.0
Date: Thu, 21 Apr 2011 22:37:59 GMT
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, GET, OPTIONS
Content-Type: text/html;charset=ISO-8859-1
요청 헤더 - POST
Host: machineA:8081
User-Agent: ... Firefox/4.01
Accept: */*
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://jquery.com/
Content-Length: 12
Origin: http://jquery.com
Pragma: no-cache
Cache-Control: no-cache
응답 헤더 - POST(상태 = 200 OK)
Content-Length: 32
Access-Control-Allow-Headers: *
Access-Control-Max-Age: 1728000
Server: CherryPy/3.2.0
Date: Thu, 21 Apr 2011 22:37:59 GMT
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, GET, OPTIONS
Content-Type: application/json
왜 한 사이트에서는 같은 요청이 실행되지만 다른 사이트에서는 실행되지 않는지 이해할 수 없습니다.제가 부족한 점을 누군가 지적해 주셨으면 합니다.도와주셔서 감사합니다!
드디어 이 링크를 발견했습니다. "A CORS POST request works from plain javascript, 하지만 왜 jQuery와 함께 하지 않는가?"는 jQuery 1.5.1이 다음 링크를 추가했음을 나타냅니다.
Access-Control-Request-Headers: x-requested-with
모든 CORS 요구에 대한 헤더입니다.jQuery 1.5.2에서는 이 작업이 수행되지 않습니다.또한 같은 질문에 따라 서버 응답 헤더 설정
Access-Control-Allow-Headers: *
는, 응답을 속행할 수 없습니다.응답 헤더에 필요한 헤더가 포함되어 있는지 확인해야 합니다.즉,
Access-Control-Allow-Headers: x-requested-with
요청:
$.ajax({
url: "http://localhost:8079/students/add/",
type: "POST",
crossDomain: true,
data: JSON.stringify(somejson),
dataType: "json",
success: function (response) {
var resp = JSON.parse(response)
alert(resp.status);
},
error: function (xhr, status) {
alert("error");
}
});
대응:
response = HttpResponse(json.dumps('{"status" : "success"}'))
response.__setitem__("Content-type", "application/json")
response.__setitem__("Access-Control-Allow-Origin", "*")
return response
구글 거리 매트릭스 API를 사용할 때 Jquery ajax에서 요청 헤더를 설정함으로써 나만의 문제를 해결했습니다. 아래를 보세요.
var settings = {
'cache': false,
'dataType': "jsonp",
"async": true,
"crossDomain": true,
"url": "https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins=place_id:"+me.originPlaceId+"&destinations=place_id:"+me.destinationPlaceId+"®ion=ng&units=metric&key=mykey",
"method": "GET",
"headers": {
"accept": "application/json",
"Access-Control-Allow-Origin":"*"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
해 주세요.
"headers": {
"accept": "application/json",
"Access-Control-Allow-Origin":"*"
}
이게 도움이 됐으면 좋겠어요.
해결책을 찾는데 시간이 좀 걸렸어요.
, 「요청」을 합니다.withCredentials: true
xhrFields
★★★★
$.ajax({
url: url,
type: method,
// This is the important part
xhrFields: {
withCredentials: true
},
// This is the important part
data: data,
success: function (response) {
// handle the response
},
error: function (xhr, status) {
// handle errors
}
});
참고: jQuery > = 1.5.1이 필요합니다.
음, 저는 이 문제로 몇 주 동안 고생했어요.
가장 쉽고, 가장 준수하며, 해킹되지 않은 방법은 브라우저 기반 호출을 하지 않고 Cross Origin 요청을 처리할 수 있는 공급자 JavaScript API를 사용하는 것입니다.
예: Facebook JavaScript API 및 Google JS API.
API 프로바이더가 최신이 아니고, 응답으로 Cross Origin Resource '*' 헤더를 지원하지 않으며, JS API(Yes I are talking you Yahoo)가 없는 경우, 3가지 옵션 중 하나가 표시됩니다.
요청에 jsonp를 사용하여 응답을 처리할 수 있는 URL에 콜백 함수를 추가합니다.주의: 요청 URL이 변경되므로 API 서버가 URL 끝에 있는 ?callback=을 처리할 수 있어야 합니다.
요청을 사용자가 제어하고 클라이언트와 동일한 도메인에 있거나 요청을 서드파티 API 서버로 프록시할 수 있는 교차 오리진 리소스 공유가 활성화된 API 서버로 보냅니다.
OAuth, OAuth, OAuth, OAuth, OAuth, OAuth, OAuth, OAuth!
window.open('url',"newwindowname",'_blank', 'toolbar=0,location=0,menubar=0')
다음은 나에게 효과가 있었던 사항의 요약입니다.
함수 정의()$.ajax
★★★★★★★★★★★★★★★★★★:
jQuery.postCORS = function(url, data, func) {
if(func == undefined) func = function(){};
return $.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json',
contentType: 'application/x-www-form-urlencoded',
xhrFields: { withCredentials: true },
success: function(res) { func(res) },
error: function() {
func({})
}
});
}
사용방법:
$.postCORS("https://example.com/service.json",{ x : 1 },function(obj){
if(obj.ok) {
...
}
});
와도 연동됩니다..done
,.fail
삭제:
$.postCORS("https://example.com/service.json",{ x : 1 }).done(function(obj){
if(obj.ok) {
...
}
}).fail(function(){
alert("Error!");
});
서버측(이 경우는 example.com 가 호스트 되고 있습니다)에서는, 다음의 헤더를 설정합니다(PHP 에 샘플 코드를 추가).
header('Access-Control-Allow-Origin: https://not-example.com');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 604800');
header("Content-type: application/json");
$array = array("ok" => $_POST["x"]);
echo json_encode($array);
이것이 JS로부터의 진정한 크로스 도메인을 POST 하는 유일한 방법입니다.
JSONP는 POST를 GET으로 변환하여 서버 로그에 중요한 정보를 표시할 수 있습니다.
【라벨】【라벨】【라벨】【라벨】【라벨】【라벨】 요구에 합니다.Access-Control-Request-Headers: x-requested-with
에, 이 「」가 되어 있는 것을 합니다.Access-Control-Allow-Headers: *
.
jquery ajax가 get requests가 정상적으로 동작하는 post requests에만 cors 문제를 준 것과 같은 문제가 있었습니다.- 위의 모든 것을 결과 없이 지쳤습니다.서버 등에 올바른 헤더가 있습니다.jquery 대신 XMLHTTPRequest를 사용하도록 전환하면 문제가 즉시 해결되었습니다.어떤 버전의 jquery를 사용해도 수정되지 않았습니다.이전 버전 브라우저 호환성이 필요하지 않은 경우에도 문제 없이 가져오기가 작동합니다.
var xhr = new XMLHttpRequest()
xhr.open('POST', 'https://mywebsite.com', true)
xhr.withCredentials = true
xhr.onreadystatechange = function() {
if (xhr.readyState === 2) {// do something}
}
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.send(json)
이것이 같은 문제를 가지고 있는 다른 사람들에게 도움이 되기를 바랍니다.
이 함수는 CORS 지원 페이지에서 HTTP 상태 응답을 비동기적으로 가져옵니다.XMLHttpRequest를 통해 액세스할 경우 GET 또는 POST 중 어느 쪽을 사용하든 적절한 헤더를 가진 페이지만 200 상태를 반환합니다.클라이언트 측에서는 이를 회피하기 위해 json 객체만 필요한 경우 JSONP를 사용하는 것 이외에는 아무것도 할 수 없습니다.
xmlHttpRequestObject 객체에 저장된 데이터를 가져오도록 다음을 변경할 수 있습니다.
function checkCorsSource(source) {
var xmlHttpRequestObject;
if (window.XMLHttpRequest) {
xmlHttpRequestObject = new XMLHttpRequest();
if (xmlHttpRequestObject != null) {
var sUrl = "";
if (source == "google") {
var sUrl = "https://www.google.com";
} else {
var sUrl = "https://httpbin.org/get";
}
document.getElementById("txt1").innerHTML = "Request Sent...";
xmlHttpRequestObject.open("GET", sUrl, true);
xmlHttpRequestObject.onreadystatechange = function() {
if (xmlHttpRequestObject.readyState == 4 && xmlHttpRequestObject.status == 200) {
document.getElementById("txt1").innerHTML = "200 Response received!";
} else {
document.getElementById("txt1").innerHTML = "200 Response failed!";
}
}
xmlHttpRequestObject.send();
} else {
window.alert("Error creating XmlHttpRequest object. Client is not CORS enabled");
}
}
}
<html>
<head>
<title>Check if page is cors</title>
</head>
<body>
<p>A CORS-enabled source has one of the following HTTP headers:</p>
<ul>
<li>Access-Control-Allow-Headers: *</li>
<li>Access-Control-Allow-Headers: x-requested-with</li>
</ul>
<p>Click a button to see if the page allows CORS</p>
<form name="form1" action="" method="get">
<input type="button" name="btn1" value="Check Google Page" onClick="checkCorsSource('google')">
<input type="button" name="btn1" value="Check Cors Page" onClick="checkCorsSource('cors')">
</form>
<p id="txt1" />
</body>
</html>
어떤 이유로 헤더를 추가하거나 제어 정책을 설정하려고 해도 아무런 효과가 없다면 apache ProxyPass 사용을 고려해 보십시오.
예를 들어, 1개의<VirtualHost>
SSL을 사용하는 경우는, 다음의 2개의 디렉티브를 추가합니다.
SSLProxyEngine On
ProxyPass /oauth https://remote.tld/oauth
다음 아파치 모듈이 로드되었는지 확인합니다(a2enmod를 사용하여 로드).
- 프록시
- proxy_connect
- proxy_module
Apache 프록시를 사용하려면 AJAX 요청 URL을 변경해야 합니다.
파티에는 조금 늦었지만, 저는 며칠 동안 이것과 씨름하고 있습니다.가능하지만 여기서 찾은 답변 중 효과가 있는 답변은 없습니다.그것은 믿을 수 없을 정도로 간단하다..ajax 호출은 다음과 같습니다.
<!DOCTYPE HTML>
<html>
<head>
<body>
<title>Javascript Test</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).domain = 'XXX.com';
$(document).ready(function () {
$.ajax({
xhrFields: {cors: false},
type: "GET",
url: "http://XXXX.com/test.php?email='steve@XXX.com'",
success: function (data) {
alert(data);
},
error: function (x, y, z) {
alert(x.responseText + " :EEE: " + x.status);
}
});
});
</script>
</body>
</html>
서버측의 php는 다음과 같습니다.
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php
header('Origin: xxx.com');
header('Access-Control-Allow-Origin:*');
$servername = "sqlxxx";
$username = "xxxx";
$password = "sss";
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) {
die( "Connection failed: " . $conn->connect_error);
}
$sql = "SELECT email, status, userdata FROM msi.usersLive";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["email"] . ":" . $row["status"] . ":" . $row["userdata"] . "<br>";
}
} else {
echo "{ }";
}
$conn->close();
?>
</body>
언급URL : https://stackoverflow.com/questions/5750696/how-to-get-a-cross-origin-resource-sharing-cors-post-request-working
'source' 카테고리의 다른 글
iframe 내부 AngularJs ng-src (0) | 2023.04.04 |
---|---|
스프링 부트 컨트롤러 엔드포인트 유닛테스트 작성 방법 (0) | 2023.04.04 |
스프링 부트 1.4테스트: 구성 오류: @Bootstrap 선언이 여러 개 발견되었습니다.와 함께 (0) | 2023.04.04 |
PowerShell : 필드 값으로 JSON 개체를 검색합니다. (0) | 2023.04.04 |
페이지 새로고침 시 리액트 라우터에서 location.state를 클리어하려면 어떻게 해야 합니까? (0) | 2023.04.04 |