Cross call working with Post but failing with pre-flight

眉间皱痕 提交于 2019-12-05 09:48:25
GreeKatrina

The reason your script is working for text/plain is because it is a simple request. If you look at this answer, you can see that your text/plain request fits the requirements for a simple request. However, when you change the content-type to text/xml it changes it to a "non-simple" request.

In order to make your "non-simple" request work, you will need to look at how to make a pre-flight request. This website explains how you can do that under "Handling a not-so-simple request".

Update

Just a Note: The Access-Control-Allow-Methods is cast sensitive (all uppercase), and you do not need to list any methods used for a simple request (GET, HEAD, POST). - source

Access-Control-Allow-Methods: OPTIONS, PUT
Access-Control-Allow-Headers: Authorization, Origin, Content-Type, Accept

Firefox doesn't include an Origin header on same-origin requests. But Chrome and Safari include an Origin header on same-origin POST/PUT/DELETE requests (same-origin GET requests will not have an Origin header).

Is there a possibility that the origin is the same?

Could there be an issue with your caching?

Make sure you have these settings for your jquery ajax call:

crossDomain: true // Will force a cross domain request
cache: false

The difference between content-type:text/plain and content-type: text/xml is: "text/xml" requires "preflight" but "text/plain" does not.

From MDN:

In particular, a request is preflighted if:

It uses methods other than GET, HEAD or POST. Also, if POST is used to send request data with a Content-Type other than application/x-www-form-urlencoded, multipart/form-data, or text/plain, e.g. if the POST request sends an XML payload to the server using application/xml or text/xml, then the request is preflighted.

Some potential reasons those can cause the fail of a preflight request:

  1. CORS is not enabled by server. Search how to enable CORS for your server technology.
  2. Server does not consume a request other than "text/plain". For example; Spring has a consume option that defines which content-type is acceptable.
  3. There is an "Authorization" header in your post. If you are sending requests with credentials, you should add Access-Control-Allow-Credentials: true header also. Again from MDN.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!