How to fix CORS error when Node API calls through Apache server

Viewed 73

I added a virtual host abc.local for 127.0.0.1

  1. Angular app is running on localhost:4000
  2. PHP API on localhost:80
  3. Node 1 API on localhost:4060
  4. Node 2 API on localhost:3001

PHP files are inside the /admin/webp folder, Node files are inside the /admin/webp/v2 and /admin/webp/v1 folder respectively.

Below is the .htaccess file

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
    Header set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
    Header set Access-Control-Allow-Credentials "true"
    Header set Access-Control-Allow-Headers "X-Requested-With, Content-Type, Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding, X-Auth-Token, content-type"
</IfModule>


<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^abc.local$
    RewriteRule ^admin/webp/v2/(.*)$ http://localhost:4060/$1 [L,R=301]
    RewriteRule ^admin/webp/v1/(.*)$ http://localhost:3001/v1/$1 [L]
</IfModule>

All rewrite rules are just working fine. For example all calls to abc.local/webp/v2/users are redirected to localhost:4060/users.

However browser throws CORS error because of the rule

RewriteRule ^admin/webp/v2/(.*)$ http://localhost:4060/$1 [L,R=301]

Apache Server responds OPTIONS request to the node application with a 301 redirect (browser is expecting a 200). Is there any workaround to fix this?

2 Answers

(Your question lacks some details, therefore forgive me if I made wrong assumptions.)

If your app wants to make a cross-origin request to http://abc.local/admin/webp/v2/users, a request header like Content-Type: application/json will cause the browser to first make a preflight request

OPTIONS http://abc.local/admin/webp/v2/users
Origin: http://localhost:4000
Access-Control-Request-Headers: Content-Type
... more Access-Control-Request-* headers ...

Because of

RewriteRule ^admin/webp/v2/(.*)$ http://localhost:4060/$1 [L,R=301]

the Apache Server responds to this OPTIONS request with a redirection

HTTP/1.1 301 Moved Permanently
Location: http://localhost:4060/admin/webp/v2/users
Access-Control-Allow-Origin: *
... other Access-Control-Allow-* headers ...

To prevent this, you could extend the RewriteCond so that it excludes OPTIONS requests from rewriting and respond to them with 200 OK.

If anyone facing the same trouble, just replace [L,R=301] with [L,P] (Requests are treated as proxy rather than redirect). It will fix the problem.

RewriteRule ^admin/webp/v2/(.*)$  http://localhost:4060/$1 [L,P]

RewriteRule ^admin/webp/v1/(.*)$  http://localhost:3001/v1/$1 [L,P]
Related