Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why my $.ajax showing "preflight is invalid redirect error"?

I tried the following code in Postman and it was working. Is there something wrong with the code?

$.ajax({    url: 'http://api.example.com/users/get',    type: 'POST',    headers: {       'name-api-key':'ewf45r4435trge',    },    data: {       'uid':36,    },    success: function(data) {       console.log(data);    } }); 

I got this error in my console as below, please advise.

XMLHttpRequest cannot load http://api.example.com/users/get Response for preflight is invalid (redirect)

like image 920
Jennifer Aniston Avatar asked Nov 11 '15 06:11

Jennifer Aniston


Video Answer


2 Answers

I received the same error when I tried to call https web service as http webservice.

e.g when I call url 'http://api.example.com/users/get' which should be 'https://api.example.com/users/get' 

This error is produced because of redirection status 302 when you try to call http instead of https.

like image 197
Peter T. Avatar answered Sep 19 '22 23:09

Peter T.


This answer goes over the exact same thing (although for angular) -- it is a CORS issue.

One quick fix is to modify each POST request by specifying one of the 'Content-Type' header values which will not trigger a "preflight". These types are:

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

ANYTHING ELSE triggers a preflight.

For example:

$.ajax({    url: 'http://api.example.com/users/get',    type: 'POST',    headers: {       'name-api-key':'ewf45r4435trge',       'Content-Type':'application/x-www-form-urlencoded'    },    data: {       'uid':36,    },    success: function(data) {       console.log(data);    } }); 
like image 45
JoshuaDavid Avatar answered Sep 20 '22 23:09

JoshuaDavid