Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Still confused about using XMLHTTPRequest cross domain

I need to POST data to a server in a different domain. That server is using SSL and expects the data to be in the form of a JSON string. I am attempting to do this from javascript.

I create the data and use JSON.stringify() to get it into the correct format. Then I send it as follows:

var url = "https://api.postageapp.com/v.1.0/send_message.json";

http=new XMLHttpRequest();
http.open("POST", url, true);

http.setRequestHeader("Content-type", "application/json");
http.setRequestHeader("Connection", "close");

// create the data in a data structure named post_data
var JSONText = JSON.stringify(post_data);
http.send(JSONText);

Doing a packet trace I see my client do a handshake with the server but then twice the server replies with "Encrypted alert" including the last time it sends a packet back. The browser debugger always shows a 405 - Method Now Allowed error.

What am I missing to get this to work? When they try it within their domain it runs fine.

like image 671
Bob Avatar asked Nov 14 '22 18:11

Bob


1 Answers

You need server to return a HTTP Header like that:

header('Access-Control-Allow-Origin: *');

Live example: Making cross domain JavaScript requests using XMLHttpRequest or XDomainRequest

like image 147
Antonio Avatar answered Jun 19 '23 21:06

Antonio