JavaScript를 통해 도메인 간 POST 요청을 보내려면 어떻게합니까?
JavaScript를 통해 도메인 간 POST 요청을 보내려면 어떻게합니까?
참고-페이지를 새로 고치면 안되며 나중에 응답을 가져와 구문 분석해야합니다.
업데이트 : 계속하기 전에 모두가 CORS에 대한 html5rocks 튜토리얼 을 읽고 이해해야합니다 . 이해하기 쉽고 매우 명확합니다.
POST되는 서버를 제어하는 경우 서버에 응답 헤더를 설정하여 "교차 출처 리소스 공유 표준"을 활용하기 만하면됩니다. 이 답변은이 스레드의 다른 답변에서 논의되지만 내 의견으로는 명확하지 않습니다.
간단히 말해서 from.com/1.html에서 to.com/postHere.php로 교차 도메인 POST를 수행하는 방법입니다 (예 : PHP 사용). 참고 : Access-Control-Allow-Origin
NON OPTIONS
요청에 대해서만 설정하면됩니다. 이 예에서는 항상 더 작은 코드 스 니펫에 대해 모든 헤더를 설정합니다.
postHere.php에서 다음을 설정하십시오.
switch ($_SERVER['HTTP_ORIGIN']) { case 'http://from.com': case 'https://from.com': header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']); header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); header('Access-Control-Max-Age: 1000'); header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With'); break; }
이렇게하면 스크립트가 도메인 간 POST, GET 및 OPTIONS를 만들 수 있습니다. 계속 읽으면 분명해질 것입니다 ...
JS에서 교차 도메인 POST를 설정합니다 (jQuery 예제) :
$.ajax({ type: 'POST', url: 'https://to.com/postHere.php', crossDomain: true, data: '{"some":"json"}', dataType: 'json', success: function(responseData, textStatus, jqXHR) { var value = responseData.someKey; }, error: function (responseData, textStatus, errorThrown) { alert('POST failed.'); } });
2 단계에서 POST를 수행하면 브라우저가 "OPTIONS"메소드를 서버로 보냅니다. 이것은 브라우저에 의한 "스 니프 (sniff)"로 서버에 POST를 수행하는 동안 멋진 지 확인합니다. 서버는 요청이 " http://from.com "또는 " https://from.com " 에서 시작된 경우 POST | GET | ORIGIN에 대한 확인을 브라우저에 알리는 "Access-Control-Allow-Origin"으로 응답합니다 . 서버가 정상이므로 브라우저는 두 번째 요청 (이번에는 POST)을 수행합니다. 클라이언트가 보내는 콘텐츠 유형을 설정하도록하는 것이 좋습니다. 따라서이를 허용해야합니다.
MDN에는 전체 흐름이 어떻게 작동하는지 자세히 설명하는 HTTP 액세스 제어 에 대한 훌륭한 글이 있습니다. 문서에 따르면 "사이트 간 XMLHttpRequest를 지원하는 브라우저에서 작동"해야합니다. 그러나 현대 브라우저 만 도메인 간 POST를 허용 한다고 생각하기 때문에 이것은 약간 오해의 소지가 있습니다. 나는 이것이 사파리, 크롬, FF 3.6에서만 작동하는지 확인했습니다.
이 경우 다음 사항에 유의하십시오.
- 서버는 작업 당 2 개의 요청을 처리해야합니다.
- 보안에 미치는 영향에 대해 생각해야합니다. 'Access-Control-Allow-Origin : *'과 같은 작업을 수행하기 전에주의하십시오.
- 이것은 모바일 브라우저에서 작동하지 않습니다. 내 경험상 크로스 도메인 POST를 전혀 허용하지 않습니다. Android, iPad, iPhone을 테스트했습니다.
- FF <3.6에는 서버가 400이 아닌 응답 코드를 반환하고 응답 본문 (예 : 유효성 검사 오류)이있는 경우 FF 3.6이 응답 본문을 얻지 못하는 매우 큰 버그가 있습니다. 좋은 REST 관행을 사용할 수 없기 때문에 이것은 엉덩이에 큰 고통입니다. 여기에서 버그를 참조 하십시오 (jQuery 아래에 제출되었지만 내 추측은 FF 버그입니다-FF4에서 수정 된 것 같습니다).
- OPTION 요청뿐만 아니라 항상 위의 헤더를 반환하십시오. FF는 POST의 응답에 필요합니다.
원격 서버를 제어하는 경우이 답변에 설명 된대로 CORS를 사용해야합니다 . IE8 이상과 FF, GC 및 Safari의 모든 최신 버전에서 지원됩니다. (그러나 IE8 및 9에서는 CORS가 요청에서 쿠키를 보내는 것을 허용하지 않습니다.)
따라서 원격 서버를 제어 하지 않거나 IE7을 지원해야하거나 쿠키가 필요하고 IE8 / 9를 지원해야하는 경우 iframe 기술을 사용하고 싶을 것입니다.
- 고유 한 이름으로 iframe을 만듭니다. (iframe은 전체 브라우저에 전역 네임 스페이스를 사용하므로 다른 웹 사이트에서 사용하지 않는 이름을 선택하세요.)
- iframe을 대상으로 숨겨진 입력이있는 양식을 구성하십시오.
- 양식을 제출하십시오.
다음은 샘플 코드입니다. IE6, IE7, IE8, IE9, FF4, GC11, S5에서 테스트했습니다.
function crossDomainPost() {
// Add the iframe with a unique name
var iframe = document.createElement("iframe");
var uniqueString = "CHANGE_THIS_TO_SOME_UNIQUE_STRING";
document.body.appendChild(iframe);
iframe.style.display = "none";
iframe.contentWindow.name = uniqueString;
// construct a form with hidden inputs, targeting the iframe
var form = document.createElement("form");
form.target = uniqueString;
form.action = "http://INSERT_YOUR_URL_HERE";
form.method = "POST";
// repeat for each parameter
var input = document.createElement("input");
input.type = "hidden";
input.name = "INSERT_YOUR_PARAMETER_NAME_HERE";
input.value = "INSERT_YOUR_PARAMETER_VALUE_HERE";
form.appendChild(input);
document.body.appendChild(form);
form.submit();
}
조심하세요! iframe이 별도의 도메인에 존재하므로 POST 응답을 직접 읽을 수 없습니다. 프레임은 다른 도메인에서 서로 통신 할 수 없습니다. 이것은 동일 출처 정책 입니다.
원격 서버를 제어하지만 CORS를 사용할 수없는 경우 (예 : IE8 / IE9를 사용하고 쿠키를 사용해야하기 때문에), 예를 들어 window.postMessage
및 / 또는 사용하여 동일 출처 정책을 해결할 수있는 방법이 있습니다. 이전 브라우저에서 교차 도메인 교차 프레임 메시지를 보낼 수있는 여러 라이브러리 중 하나 :
원격 서버를 제어하지 않으면 POST 응답을 읽을 수 없습니다. 그렇지 않으면 보안 문제가 발생할 수 있습니다.
- iFrame 만들기,
- 숨겨진 입력으로 양식을 입력하고,
- 양식의 작업을 URL로 설정하고
- 문서에 iframe 추가
- 양식 제출
의사 코드
var ifr = document.createElement('iframe');
var frm = document.createElement('form');
frm.setAttribute("action", "yoururl");
frm.setAttribute("method", "post");
// create hidden inputs, add them
// not shown, but similar (create, setAttribute, appendChild)
ifr.appendChild(frm);
document.body.appendChild(ifr);
frm.submit();
iframe의 스타일을 숨기고 절대적으로 배치하고 싶을 것입니다. 크로스 사이트 게시가 브라우저에서 허용되는지 확실하지 않지만, 그렇다면 이것이 방법입니다.
간단하게 유지 :
교차 도메인 POST :
사용crossDomain: true,
페이지를 새로 고치면 안 됨 :
아니요,서버가 응답을 다시 보낼 때success
또는error
비동기 콜백이 호출되므로페이지를 새로 고치지 않습니다.
예제 스크립트 :
$.ajax({
type: "POST",
url: "http://www.yoururl.com/",
crossDomain: true,
data: 'param1=value1¶m2=value2',
success: function (data) {
// do something with server response data
},
error: function (err) {
// handle your error logic here
}
});
관련된 모든 서버에 액세스 할 수있는 경우 다른 도메인에서 요청중인 페이지에 대한 응답 헤더에 다음을 입력하십시오.
PHP :
header('Access-Control-Allow-Origin: *');
예를 들어, Drupal의 xmlrpc.php 코드에서 다음을 수행합니다.
function xmlrpc_server_output($xml) {
$xml = '<?xml version="1.0"?>'."\n". $xml;
header('Connection: close');
header('Content-Length: '. strlen($xml));
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/x-www-form-urlencoded');
header('Date: '. date('r'));
// $xml = str_replace("\n", " ", $xml);
echo $xml;
exit;
}
이로 인해 보안 문제가 발생할 수 있으므로 요청을 확인하기 위해 적절한 조치를 취해야합니다.
http://taiyolab.com/mbtweet/scripts/twitterapi_call.js 에서 post_method
함수를 확인하세요 . 위에서 설명한 iframe 메서드의 좋은 예입니다.
두 개의 숨겨진 iframe을 만듭니다 (css 스타일에 "display : none;"추가). 두 번째 iframe이 자신의 도메인에있는 항목을 가리 키도록합니다.
숨겨진 양식을 만들고 해당 메서드를 target = 첫 번째 iframe으로 "post"로 설정하고 선택적으로 enctype을 "multipart / form-data"로 설정합니다 (그림과 같은 다중 부분 데이터를 보내려고하기 때문에 POST를 수행하고 싶다고 생각합니다. ?)
준비가되면 제출 () 양식을 POST로 만드십시오.
다른 도메인이 Iframe ( http://softwareas.com/cross-domain-communication-with-iframes ) 과의 교차 도메인 통신을 수행 할 자바 스크립트를 반환하도록 할 수 있다면 운이 좋으며 응답을 캡처 할 수 있습니다. 게다가.
물론 서버를 프록시로 사용하려면이 모든 것을 피할 수 있습니다. 양식을 자신의 서버에 제출하면 요청이 다른 서버로 프록시되고 (다른 서버가 IP 불일치를 감지하도록 설정되지 않은 경우) 응답을 받고 원하는 것을 반환합니다.
주목해야 할 또 하나의 중요한 것 !!! 위의 예 에서는 사용 방법에 대해 설명합니다.
$.ajax({
type : 'POST',
dataType : 'json',
url : 'another-remote-server',
...
});
JQuery 1.6 이하에는 교차 도메인 XHR에 버그가 있습니다. Firebug에 따르면 OPTIONS를 제외한 요청이 전송되지 않았습니다. POST가 없습니다. 조금도.
내 코드를 테스트 / 튜닝하는 데 5 시간이 걸렸습니다. 원격 서버 (스크립트)에 많은 헤더 추가. 아무 효과없이. 그러나 나중에 JQuery lib를 1.6.4로 업데이트했으며 모든 것이 매력처럼 작동합니다.
JQuery AJAX를 사용하여 ASP.net MVC 환경에서이 작업을 수행하려면 다음 단계를 수행하십시오. ( 이 스레드 에서 제공하는 솔루션 요약입니다 )
"caller.com"(모든 웹 사이트 일 수 있음)이 "server.com"(ASP.net MVC 응용 프로그램)에 게시해야한다고 가정합니다.
"server.com"앱의 Web.config에서 다음 섹션을 추가합니다.
<httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> <add name="Access-Control-Allow-Headers" value="Content-Type" /> <add name="Access-Control-Allow-Methods" value="POST, GET, OPTIONS" /> </customHeaders> </httpProtocol>
"server.com"에서 게시 할 컨트롤러 ( "홈"이라고 함)에 대해 다음 작업을 수행합니다.
[HttpPost] public JsonResult Save() { //Handle the post data... return Json( new { IsSuccess = true }); }
그런 다음 "caller.com"에서 다음과 같이 양식 (html id "formId")의 데이터를 "server.com"에 게시합니다.
$.ajax({ type: "POST", url: "http://www.server.com/home/save", dataType: 'json', crossDomain: true, data: $(formId).serialize(), success: function (jsonResult) { //do what ever with the reply }, error: function (jqXHR, textStatus) { //handle error } });
상위 수준 .... other-serve.your-server.com이 other-server.com을 가리 키도록 서버에 cname을 설정해야합니다.
귀하의 페이지는 other-server.com으로의 전송 역할을하는 보이지 않는 iframe을 동적으로 생성합니다. 그런 다음 JS를 통해 페이지에서 other-server.com으로 통신하고 데이터를 페이지로 다시 반환하는 콜백을 받아야합니다.
가능하지만 your-server.com 및 other-server.com의 조정이 필요합니다.
가장 좋은 방법은 XMLHttpRequest (예 : jQuery의 $ .ajax (), $ .post ())를 Cross-Origin Resource Sharing polyfills https://github.com/Modernizr/Modernizr/wiki/HTML5- 와 함께 사용하는 것입니다. 크로스 브라우저 Polyfills # wiki-CORS
한 가지 더 방법이 있습니다 (html5 기능 사용). 다른 도메인에서 호스팅되는 프록시 iframe을 사용하고, postMessage를 사용하여 해당 iframe에 메시지를 보낸 다음 해당 iframe이 POST 요청 (동일한 도메인에서)을 수행하고 postMessage를 상위 창에 다시 배치 할 수 있습니다.
sender.com의 부모
var win = $('iframe')[0].contentWindow
function get(event) {
if (event.origin === "http://reciver.com") {
// event.data is response from POST
}
}
if (window.addEventListener){
addEventListener("message", get, false)
} else {
attachEvent("onmessage", get)
}
win.postMessage(JSON.stringify({url: "URL", data: {}}),"http://reciver.com");
reciver.com의 iframe
function listener(event) {
if (event.origin === "http://sender.com") {
var data = JSON.parse(event.data);
$.post(data.url, data.data, function(reponse) {
window.parent.postMessage(reponse, "*");
});
}
}
// don't know if we can use jQuery here
if (window.addEventListener){
addEventListener("message", listener, false)
} else {
attachEvent("onmessage", listener)
}
This is an old question, but some new technology might help someone out.
If you have administrative access to the other server then you can use the opensource Forge project to accomplish your cross-domain POST. Forge provides a cross-domain JavaScript XmlHttpRequest wrapper that takes advantage of Flash's raw socket API. The POST can even be done over TLS.
The reason you need administrative access to the server you are POSTing to is because you must provide a cross-domain policy that permits access from your domain.
http://github.com/digitalbazaar/forge
I know this is an old question, but I wanted to share my approach. I use cURL as a proxy, very easy and consistent. Create a php page called submit.php, and add the following code:
<?
function post($url, $data) {
$header = array("User-Agent: " . $_SERVER["HTTP_USER_AGENT"], "Content-Type: application/x-www-form-urlencoded");
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
$url = "your cross domain request here";
$data = $_SERVER["QUERY_STRING"];
echo(post($url, $data));
Then, in your js (jQuery here):
$.ajax({
type: 'POST',
url: 'submit.php',
crossDomain: true,
data: '{"some":"json"}',
dataType: 'json',
success: function(responseData, textStatus, jqXHR) {
var value = responseData.someKey;
},
error: function (responseData, textStatus, errorThrown) {
alert('POST failed.');
}
});
Should be possible with a YQL custom table + JS XHR, take a look at: http://developer.yahoo.com/yql/guide/index.html
I use it to do some client side (js) html scraping, works fine (I have a full audio player, with search on internet/playlists/lyrics/last fm informations, all client js + YQL)
CORS is for you. CORS is "Cross Origin Resource Sharing", is a way to send cross domain request.Now the XMLHttpRequest2 and Fetch API both support CORS, and it can send both POST and GET request
But it has its limits.Server need to specific claim the Access-Control-Allow-Origin, and it can not be set to '*'.
And if you want any origin can send request to you, you need JSONP (also need to set Access-Control-Allow-Origin, but can be '*')
For lots of request way if you don't know how to choice, I think you need a full functional component to do that.Let me introduce a simple component https://github.com/Joker-Jelly/catta
If you are using modern browser (> IE9, Chrome, FF, Edge, etc.), Very Recommend you to use a simple but beauty component https://github.com/Joker-Jelly/catta.It have no dependence, Less than 3KB, and it support Fetch, AJAX and JSONP with same deadly sample syntax and options.
catta('./data/simple.json').then(function (res) {
console.log(res);
});
It also it support all the way to import to your project, like ES6 module, CommonJS and even <script>
in HTML.
If you have access to the cross domain server and don't want to make any code changes on server side, you can use a library called - 'xdomain'.
How it works:
Step 1: server 1: include the xdomain library and configure the cross domain as a slave:
<script src="js/xdomain.min.js" slave="https://crossdomain_server/proxy.html"></script>
Step 2: on cross domain server, create a proxy.html file and include server 1 as a master:
proxy.html:
<!DOCTYPE HTML>
<script src="js/xdomain.min.js"></script>
<script>
xdomain.masters({
"https://server1" : '*'
});
</script>
Step 3:
Now, you can make an AJAX call to the proxy.html as endpoint from server1. This is bypass the CORS request. The library internally uses iframe solution which works with Credentials and all possible methods: GET, POST etc.
Query ajax code:
$.ajax({
url: 'https://crossdomain_server/proxy.html',
type: "POST",
data: JSON.stringify(_data),
dataType: "json",
contentType: "application/json; charset=utf-8"
})
.done(_success)
.fail(_failed)
참고URL : https://stackoverflow.com/questions/298745/how-do-i-send-a-cross-domain-post-request-via-javascript
'IT박스' 카테고리의 다른 글
SQL Server 트랜잭션 로그를 어떻게 지우나요? (0) | 2020.10.04 |
---|---|
배경 아래에 나타나는 부트 스트랩 모달 (0) | 2020.10.04 |
WPF에서 x : Name 및 Name 특성의 차이점은 무엇입니까? (0) | 2020.10.04 |
( 'b'+ 'a'+ + 'a'+ 'a'). toLowerCase () 'banana'의 결과는 무엇입니까? (0) | 2020.10.04 |
프로세스 내부에서 CPU 및 메모리 사용량을 확인하는 방법은 무엇입니까? (0) | 2020.10.04 |