I’m trying send a post to my server, but Ionic change the method from post to options.
I have this method:
drugstores(product_name, points) {
var url = this.ROOT_URL + ‘/drugstores’;
var data = JSON.stringify({
product_name: product_name,
points: points
});
let headers = new Headers({
'Content-Type': 'application/x-www-form-urlencoded'
});
let options = new RequestOptions({
headers: headers
});
var response = this.http.post(url, data, options).timeout(this.TIMEOUT).map(res => res.json());
return response;
}
And this method go as POST, but I need change the headers to application/json, so I change my headers to this:
let headers = new Headers({
‘Content-Type’: ‘application/json’
});
But it’s changes my method from POST to OPTIONS.
How I can send json and keep the method as post?
This is called a preflight and is performed by your browser, not Ionic. Normally preflights are not performed on POST, HEAD or GET requests, but something in your request is triggering the preflight to happen, specifically you setting the Content-Type
to application/json
, I believe. The goal isn’t to get around the preflight, but to handle it.
Before I continue, I’m assuming you have an error in your console saying something about preflight and Access-Control-Allow-Origin? Can you paste the whole thing? Also, what is your backend written in?
2 Likes
You’re right, @mich356c ! Thanks, when I run it on my device it’s works!
In my browser console I got this:
XMLHttpRequest cannot load http://192.168.0.5:3000/ws/drugstores. Response for preflight has invalid HTTP status code 404
I’m using Rails and I put it on my method to handle CORS problem that I have before.
headers[‘Access-Control-Allow-Origin’] = ‘’
headers[‘Access-Control-Allow-Methods’] = ‘POST, PUT, DELETE, GET, OPTIONS’
headers[‘Access-Control-Request-Method’] = '’
headers[‘Access-Control-Allow-Headers’] = ‘Origin, X-Requested-With, Content-Type, Accept, Authorization’
In my server I got this error: (No route matches [OPTIONS] “/ws/drugstores”) because I have any options router.
–
So, you know how can I handle it? Build and run always in my device/emulator makes my dev day slow.
Setup a route for the preflight requests, for the method OPTIONS and all routes (*). Not sure how it works with Rails, never used it before. I assume you’d just set the headers again, and then it’d automatically return an error if it doesn’t match, otherwise if all is good send a 200 OK
I solve this on server side. I thought there’s some easy soluction on Ionic.
Just to let here to help others:
I insert the rack-cors gem and use your default config. Works fine!
config.middleware.insert_before 0, Rack::Cors do
allow do
origins ‘’
resource '’, :headers => :any, :methods => [:get, :post, :options]
end
end