简体   繁体   English

jQuery跨域POST shenanigans

[英]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"}. 我正在尝试对API进行身份验证,该API仅允许您使用带有JSON的POST作为表单数据进行身份验证,格式为{“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. 我已经尝试了两天来使用jQuery,但是我遇到了问题,因为它是跨域的。 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仅接受授权的POST
  • API requires json as form data, example: {"username":"myusername","password":"mypassword"} API需要json作为表单数据,例如:{“username”:“myusername”,“password”:“mypassword”}
  • The js is ran from a different domain, causing cross domain errors js从不同的域运行,导致跨域错误

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. 您的本地JS将对本地URL执行ajax发布,该URL将接受带有json数据的POST方法。

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. 此时,您的服务器代码将使用适当的数据向远程服务器执行HTTP POST,获取响应,并将其发送回调用的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. 问题是您尝试POST的域不响应在每个跨域请求之前发送的OPTIONS请求。 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. 使用OPTIONS请求,浏览器会收到有关跨域规则等的信息。要启用跨域请求,服务器必须设置Access-Control-Allow-Origin:* (或实际上是脚本的域,但*涵盖所有内容)并且可能是Access-Control-Allow-Methods: GET, POST, OPTIONS标题。

I have a shared hosting on GoDaddy. 我在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. 我写了一个.htaccess文件,把它放在与我的操作页面相同的文件夹中。 Here are the contents of the .htaccess file: 以下是.htaccess文件的内容:

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电话:

    $.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 .htaccess中的头设置Access-Control-Allow-Origin不起作用

For cross domain stuff use JSONP (search for crossDomain) 对于跨域的东西,使用JSONP (搜索crossDomain)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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