vicusbass
vicusbass

Reputation: 1804

How do I avoid Cross origin requests issues when doing POST with JQuery (and Sinatra)

I have a HTML + KnockoutJS + JQuery site deployed under Apache on my machine, accesible at http://daily/admin.html (or http://localhost/admin.html). The backend is built in Sinatra and runs under rackup, so I can access its API at http://localhost:9292/api/items The problem is that if I do an AJAX GET request, I get:

XMLHttpRequest cannot load http://localhost:9292/api/items. Origin http://localhost is not allowed by Access-Control-Allow-Origin.

My fix was to add the following line to the Sinatra app:

headers['Access-Control-Allow-Origin'] = 'http://daily'

Problem is that now I cannot do a POST using Ajax. I got the following message:

Cross origin requests are only supported for HTTP.

Is JSONP an option? Can I use JSONP for POST?

Upvotes: 0

Views: 362

Answers (1)

minhnhat2807
minhnhat2807

Reputation: 11

You can use JSONP for this case.

With this code above, I think you miss something

headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept'
headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, DELETE, OPTIONS'

Upvotes: 1

Related Questions