BACKGROUND
First things first, I have a Restify service running on Node which is working perfectly when I use a GUI HTTP client. I only state the previous to highlight, that this is a browser-centric issue. And if a server-side solution is needed, it is to accomodate the browser...
Here are the 100% functional HTTP requests and responses using my Restify web service and a GUI HTTP client:
Request -
POST /appointments HTTP/1.1
Content-Type: application/json
Accept: application/json
Host: localhost:8085
Connection: close
User-Agent: Paw/2.1.1 (Macintosh; OS X/10.10.1) GCDHTTPRequest
Content-Length: 142
{
"eventName": "Fiesta Forever",
"time": "Fri Dec 19 2014 15:55:00 GMT-0600 (CST)",
"phoneNumber": "13125555555"
}
Response-
HTTP/1.1 201 Created
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Max-Age: 1000
Content-Type: application/json
Content-Length: 37
Date: Fri, 19 Dec 2014 23:01:29 GMT
Connection: close
{"message":"Alright Alright Alright"}
And more importantly, my server creates a future cron job, which can be seen in my server's console:
Created: Fri Dec 19 2014 14:55:00 GMT-0600 (CST)
THE PROBLEM
My problem is that I am trying to write a browser interface to my service. And I am getting an error when I try making the same HTTP request using Ajax. I created the following test function which makes the HTTP request:
function testPost() {
var jsonBody = "{\"eventName\": \"Fiesta Forever\",\"time\": \"Fri Dec 19 2014 14:15:00 GMT-0600 (CST)\",\"phoneNumber\": \"13125555555\"}";
$.ajax({
url: 'http://localhost:8085/appointments',
accepts: 'application/json',
type: 'POST',
data: jsonBody,
contentType: 'application/json',
crossDomain: true,
headers: {
"Access-Control-Allow-Origin":true
}
});
}
I then load my page containing that function in my iOS emulator, and call the function from the Safari Developer console. I receive the following error:
EDIT: Upon removing the request headers, I receive:
Failed to load resource: the server responded with a status of 406 (Not Acceptable)
SERVER-CODE
Here is the code on my server. I took the following code from the Express docs, because they were the only solution which actually seemed to add the correct headers to every response:
//CORS
server.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
res.header("Access-Control-Max-Age", "1000");
next();
});
Can anyone help me figure out how to make a cross domain HTTP request using $.ajax which carries and receives JSON?