Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...