jQuery 跨域 POST 恶作剧

发布于 2024-11-25 03:20:52 字数 892 浏览 0 评论 0原文

我正在尝试对 API 进行身份验证,该 API 只允许您使用以 JSON 作为表单数据的 POST 进行身份验证,格式为 {"username":"myusername","password":"mypassword"}。

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

错误消息:

Request Method:OPTIONS
Status Code:405 METHOD NOT ALLOWED

到目前为止的代码:

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);
    }
})

总结一下:

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

非常感谢您的帮助:)

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 :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

裸钻 2024-12-02 03:20:52

你应该遵循不同的模式。您的本地 JS 将对本地 URL 执行 ajax post,该 URL 将接受包含 json 数据的 POST 方法。

此时,您的服务器代码将使用正确的数据向远程服务器执行 HTTP POST,获取响应,并将其发送回调用 js。

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.

远山浅 2024-12-02 03:20:52

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

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.

琴流音 2024-12-02 03:20:52

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

我编写了一个 .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"

这是我的 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
    });

请参阅这篇文章以供参考:

.htaccess 中的标头设置 Access-Control-Allow-Origin 不起作用

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

终陌 2024-12-02 03:20:52

对于跨域内容,请使用 JSONP (搜索 crossDomain)

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

For cross domain stuff use JSONP (search for crossDomain)

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文