问题描述
我尝试对一个API进行身份验证,只允许使用JSON作为表单数据进行身份验证,格式为{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
>
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);
}
})
总结:
- API只接受POST for auth
- API需要json作为表单数据,例如:{username:myusername,password:mypassword}
- js从不同的域运行,导致跨域错误
)
推荐答案
您应该遵循不同的模式。你的本地JS会做一个ajax post到一个本地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 shenanigans的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!