Cross Origin Resource sharing issue even when all the CORS headers are present

前端 未结 2 922
無奈伤痛
無奈伤痛 2021-01-23 13:35

even though i have appended my service response with following provided CORS Headers :

resp.setContentType(\"application/json\");
resp.addHeader(\"Access-         


        
2条回答
  •  孤独总比滥情好
    2021-01-23 13:44

    I think the problem here is Preflighted Requests in CORS.

    From the Mozilla docs,

    Unlike simple requests (discussed above), "preflighted" requests first send an HTTP request by the OPTIONS method to the resource on the other domain, in order to determine whether the actual request is safe to send. Cross-site requests are preflighted like this since they may have implications to user data. 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
      • 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.

    • It sets custom headers in the request (e.g. the request uses a header such as X-PINGOTHER)

    As explained above, even though you're making a simple POST request, the Content-Type in your request is application/json which is different from the 3 types mentioned above, so it's considered as a Preflight request and an OPTIONS request is fired before your actual POST request.

    You can solve this by implementing doOptions in your servlet, just add the headers there and it will work :)

提交回复
热议问题