jQuery cross domain POST shenanigans

前端 未结 4 1177
北海茫月
北海茫月 2020-12-09 10:16

I\'m trying to authenticate to an API, which only allows you to authenticate using a POST with JSON as form data, in the format of {\"username\":\"myusername\",\"password\":

相关标签:
4条回答
  • 2020-12-09 10:36

    You should follow a different pattern. Your local JS will do an ajax post to a local URL which will accept the POST method with your json data.

    At this point your server code will do an HTTP POST with proper data to the remote server, get the response, and send it back to the calling js.

    0 讨论(0)
  • 2020-12-09 10:43

    For cross domain stuff use JSONP (search for crossDomain)

    http://www.ibm.com/developerworks/library/wa-aj-jsonp1/

    0 讨论(0)
  • 2020-12-09 10:46

    The problem is that the domain you are trying to POST to doesn't respond to the OPTIONS request that is sent before each cross-domain request. With the OPTIONS request, the browser receives information about cross domain rules etc. To enable the cross domain request, the server has to set Access-Control-Allow-Origin:* (or the domain of the script, actually, but * covers everything) and maybe Access-Control-Allow-Methods: GET, POST, OPTIONS headers.

    0 讨论(0)
  • 2020-12-09 10:54

    I have a shared hosting on GoDaddy. I needed an answer to this question, too, and after searching around I found that it is possible.

    I wrote an .htaccess file, put it in the same folder as my action page. Here are the contents of the .htaccess file:

    Header add Access-Control-Allow-Origin "*"
    Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
    Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
    

    Here is my ajax call:

        $.ajax({
            url: 'http://www.mydomain.com/myactionpagefolder/gbactionpage.php',  //server script to process data
            type: 'POST',
            xhr: function() {  // custom xhr
                myXhr = $.ajaxSettings.xhr();
                if(myXhr.upload){ // check if upload property exists
                    myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // for handling the progress of the upload
                }
                return myXhr;
            },
            //Ajax events
            beforeSend: beforeSendHandler,
            success: completeHandler,
            error: errorHandler,
            // Form data
            data: formData,
            //Options to tell JQuery not to process data or worry about content-type
            cache: false,
            contentType: false,
            processData: false
        });
    

    See this article for reference:

    Header set Access-Control-Allow-Origin in .htaccess doesn't work

    0 讨论(0)
提交回复
热议问题