jQuery 跨域 POST 恶作剧 [英] jQuery cross domain POST shenanigans

查看:27
本文介绍了jQuery 跨域 POST 恶作剧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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?

错误信息:

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从不同的域运行,导致跨域错误

非常感谢您的帮助:)

推荐答案

您应该遵循不同的模式.您的本地 JS 将向本地 URL 执行 ajax 发布,该 URL 将接受带有您的 json 数据的 POST 方法.

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.

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

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.

这篇关于jQuery 跨域 POST 恶作剧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆