Javascript jQuery 跨域 POST 恶作剧

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6761982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:04:57  来源:igfitidea点击:

jQuery cross domain POST shenanigans

javascriptjqueryjsonpostcross-domain

提问by FLX

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. How can I accomplish this?

我已经尝试了两天来让这个与 jQuery 一起工作,但我遇到了问题,因为它是跨域的。我怎样才能做到这一点?

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
  • API 只接受 POST 进行身份验证
  • API 需要 json 作为表单数据,例如:{"username":"myusername","password":"mypassword"}
  • js从不同的域运行,导致跨域错误

Your help is much appreciated :)

非常感谢您的帮助 :)

采纳答案by Matteo Mosca

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。

回答by zatatatata

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, OPTIONSheaders.

问题是您尝试 POST 的域不响应在每个跨域请求之前发送的 OPTIONS 请求。通过 OPTIONS 请求,浏览器接收有关跨域规则等的信息。要启用跨域请求,服务器必须设置Access-Control-Allow-Origin:*(或脚本的域,实际上,但 * 涵盖了所有内容)和Access-Control-Allow-Methods: GET, POST, OPTIONS标头。

回答by TARKUS

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.

我在 GoDaddy 上有一个共享主机。我也需要这个问题的答案,在四处搜索后我发现这是可能的。

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

我写了一个 .htaccess 文件,将它放在与我的操作页面相同的文件夹中。以下是 .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 不起作用

回答by marto

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/