http post request with cross-origin in javascript

落花浮王杯 提交于 2019-12-07 05:21:18

问题


i have a problem with a http post call in firefox. I know that when there are a cross origin, firefox first do a OPTIONS before the POST to know the access-control-allow headers. With this code i dont have any problem:

Net.requestSpeech.prototype.post = function(url, data) {
    if(this.xhr != null) {
        this.xhr.open("POST", url);
        this.xhr.onreadystatechange = Net.requestSpeech.eventFunction;
        this.xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        this.xhr.send(data);
    }
}

I test this code with a simple html that invokes this function. Everything is ok and i have the response of the OPTIONS and POST, and i process the response. But, i'm trying to integrate this code with an existen application with uses jquery (i dont know if this is a problem), when the send(data) executes in this case, the browser (firefox) do the same, first do a OPTION request, but in this case dont receive the response of the server and puts this message in console:

[18:48:13.529] OPTIONS http://localhost:8111/ [undefined 31ms]

Undefined... the undefined is because dont receive the response, but the code is the same, i dont know why in this case the option dont receive the response, someone have an idea?

i debug my server app and the OPTIONS arrive ok to the server, but it seems like the browser dont wait to the response.

edit more later: ok i think that the problem is when i run with a simple html with a SCRIPT tag that invokes the method who do the request run ok, but in this app that dont receive the response, i have a form that do a onsubmit event, i think that the submit event returns very fast and the browser dont have time to get the OPTIONS request.

edit more later later: WTF, i resolve the problem make the POST request to sync:

this.xhr.open("POST", url, false);

The submit reponse very quickly and can't wait to the OPTION response of the browser, any idea to this?


回答1:


Due to the same origin policy, you can't send cross origin post, you can workaround it by include sites in iframes (if have access to the domain) original site contains iframe to the outer site, the inner direction is legal.



来源:https://stackoverflow.com/questions/8231434/http-post-request-with-cross-origin-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!