简体   繁体   中英

jQuery cross domain POST shenanigans

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":"mypassword"}.

I've been trying for two days to get this working with jQuery but I'm running into problems because it's cross domain. How can I accomplish this?

Error message:

Request Method:OPTIONS
Status Code:405 METHOD NOT ALLOWED

Code up till now:

var username = "myusername";
var password = "mypass"
var authurl = "https://myurl";

$.ajax
({
    type: "POST",
    url: authurl,
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    async: false,
    data: {'json':'{"username":"' + username + '", "password":"' + password + '"}'},
    success: function (result) {
        $('#json').html(result);
    }
})

To summarize:

  • API only accepts POST for auth
  • API requires json as form data, example: {"username":"myusername","password":"mypassword"}
  • The js is ran from a different domain, causing cross domain errors

Your help is much appreciated :)

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.

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.

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

For cross domain stuff use JSONP (search for crossDomain)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM