CORS header 'Access-Control-Allow-Origin' missing only in browser/jquery but OK with curl

- 1 answer

Ad

The problem is that I get different header responses in Browser vs Curl command

I've got mypage.com (client html/css/js) served by nginx on port 8081 in my local host.

I access it from a browser on http://mypage.com:8081 (mypage.com mapped to -> 127.0.0.1 on /etc/hosts).

Page loads fine and it does a first jQuery request.

GET http://mypage.com:8081/api/foo

I've got Tomcat 8 running my 2 REST APIs in port :9090

As target is :8081 request gets resolved in nginx

location /services
         proxy_pass         http://127.0.0.1:9090/services/
location /api
         proxy_pass         http://127.0.0.1:9090/api/

** =======Everything fine so far.==========**

Second request in JQuery is

GET http://mypage.com:9090/services/foo

As the current page in the browser is mypage.com:8081 and JQuery call is targeted to mypage.com:9090/services/foo ; browser detects a CORS request.

In the request, 'Origin: http://mypage.com:8081' header is set but no Access-Control-Allow-Origin comes back. It simply does not.

OPTIONS http://mypage.com:9090/ returns 403 **ONLY in the browser**

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://mypage.com:9090/service/bar (Reason: CORS header 'Access-Control-Allow-Origin' missing).

I've checked Tomcat's configuration, added CORS filters and I can confirm through CURL everything is working fine when I execute the same command the browser does.

I'm running in circles with this one. - CORS Origin header is set in both cases - in Browser , result is 403 and response headers don't show anything else than

Content-Length: 87
Content-Type: text/plain;charset=ISO-8859-1
Date: Wed, 23 Dec 2015 01:11:53 GMT
Server: Apache-Coyote/1.1
  • in curl command though, same request produces a response where the Access-Control-Allow-Origin is set to the origin passed on the request header.

Question : why browser OPTIONS returns no Access-Control-Allow-Origin? I can't seem to be able to reproduce it by hitting the same URL with the same verb with same arguments but through CURL command

Ad

Answer

Ad

I found the problem at the end with this.

Following Tomcat's CORS flowchart I narrowed the problem to the fact there was a mismatch between the headers I was sending from the client and the ones supported in the backend.

The solution was to overwrite defaults in tomcat's filter by adding my custom header

<init-param>
            <param-name>cors.allowed.headers</param-name>
            <param-value>....,X-My-Custom,...</param-value>
</init-param>
Ad
source: stackoverflow.com
Ad