2

Ok, Im using REST Console (Chrome extension) to test a rest API. The requests work with the REST Console, but doing the same in javascript AJAX it fails with Origin localhost:8000 is not allowed by Access-Control-Allow-Origin.

The server is setup to allow *, and I can see this in the REST Console's response headers. But looking at the my response Headers when doing a ajax request in javascript, I see that those headers is not there.

What is the difference between the two?

Here is my simple AJAX request (coffeescript)

$.ajax
    type: requestType
    contentType: "application/json"
    url: url
    data: data_string
    success: (r) =>
        successCallback(r)
    error: (r) =>
        errorCallback(r)

This works at the office in the local network, now on the VPN it does not. But REST Console always works??

Harry
  • 13,091
  • 29
  • 107
  • 167

1 Answers1

3

application/json is not allowed for Content-Type: in a simple CORS request.

It has to be preflighted, and the server side setup for that is a bit more complex.

Try unsetting contentType or using one of these, if appropriate:

  • application/x-www-form-urlencoded
  • multipart/form-data
  • text/plain

see also my previous answer here

and a related question:

jQuery CORS Content-type OPTIONS

Community
  • 1
  • 1
Paul
  • 26,170
  • 12
  • 85
  • 119
  • Thanks for this, it does not seem to make any difference. Still getting the response if I take it out. Or should it be a different content type? – Harry Aug 20 '13 at 08:29
  • Wait, seems to be working now. But now the other dev who im testing to is offline! lol – Harry Aug 20 '13 at 08:31
  • 1
    Does the server send the header `Access-Control-Allow-Origin: *` ? – Paul Aug 20 '13 at 08:31
  • Yes it does, but previously only to the REST Console app, not javascript AJAX call. Ill have to wait for other dev to get back – Harry Aug 20 '13 at 08:33
  • Looking at my notes on a project with preflight, I can't find the change in the $.ajax call in the code, so that might be the same. On the server side, though, you need to handle http OPTIONS requests. Also, don't preflight unless you really need it, it makes two requests out of one and takes more time. – Paul Aug 20 '13 at 08:40
  • Hey, just tested and it did not make any difference – Harry Aug 20 '13 at 08:54
  • Are you (or can you) use Chrome on the browser side? – Paul Aug 20 '13 at 08:55
  • If you do so, you can click the "Network" tab of the dev tools, and see what the browser is sending and receiving. Furthermore, some parts of the table under "Network" is clickable for more information. – Paul Aug 20 '13 at 08:56