CORS issue

I am facing CORS issue as below:

Access to XMLHttpRequest at ‘https://78831182-pvgk9v0mm-wedothebest4yous-projects.vercel.app/’ from origin ‘http://localhost:3002’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.Understand this error
(index):21 Q {message: ‘Network Error’, name: ‘AxiosError’, code: ‘ERR_NETWORK’, config: {…}, request: XMLHttpRequest, …}
xhr.js:258

   GET https://78831182-pvgk9v0mm-wedothebest4yous-projects.vercel.app/ net::ERR_FAILED 401 (Unauthorized)

My vercel.json is this:

{
“version”: 2,
“builds”: [
{
“src”: “api/server.js”,
“use”: “@vercel/node”
}
],
“routes”: [
{
“src”: “/(.)",
“dest”: “api/server.js”,
“methods”: [“GET”, “POST”, “PUT”, “DELETE”, “PATCH”, “OPTIONS”],
“headers”: {
“Access-Control-Allow-Origin”: "

}
}
]
}

I followed this guide : How can I enable CORS on Vercel?

Request your valuable help.
WeDotheBest4You.

Hello and welcome, @wedothebest4you! We need to know more about your project. If you can share more info about the project and how you’re running it, that would help us understand what’s happening.

A minimal reproducible example is usually the fastest way to let others see what you see so we can help you debug the problem.

1 Like

Hi, Thank you for your response. I shall provide the requested information soon.

Please see below a MRE.

server.js

const express = require('express');

const app = express();

app.get('/', (req, res) => {
  res.send('done');
});

app.listen(4000, () => {
  console.log(`L@4000`);
});

module.exports = app;

vercel.json

{
  "version": 2,
  "rewrites": [{ "source": "/(.*)", "destination": "/api/index.js" }],
  "headers": [
    {
      "source": "/(.*)",
      "headers": [
        { "key": "Access-Control-Allow-Credentials", "value": "true" },
        { "key": "Access-Control-Allow-Origin", "value": "*" },
        {
          "key": "Access-Control-Allow-Methods",
          "value": "GET,OPTIONS,PATCH,DELETE,POST,PUT"
        },
        {
          "key": "Access-Control-Allow-Headers",
          "value": "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version"
        }
      ]
    }
  ]
}

Test run 1

Request URL  No CORS involved.
https://new-express-project-p61e9hmrr-wedothebest4yous-projects.vercel.app 
CORS : No CORS, the URL executed directly from Browser.
Result expected : done
Result received : done
Status : Produced the desired output

Test run 2

Request URL (the same one): https://new-express-project-p61e9hmrr-wedothebest4yous-projects.vercel.app 
Executed as : CORS
origin : http://localhost:2000
document : "index.html" as shown below:
Code : The document fetches the URL on load. The actual code also provided below.
Result expected : done
Result received : Network error in console, details provided below.
Status : Need guidance to correct the CORS configuration.

index.html

  <script>
    const p = document.querySelector('p');
    const host =
      'https://new-express-project-p61e9hmrr-wedothebest4yous-projects.vercel.app ';

    fetch(host, {
      method: 'GET',
      credentials: 'include',
    })
      .then((response) => {
        if (!response.ok) {
          p.textContent = 'Error occured';
        }
        return response.text();
      })
      .then((data) => {
        p.textContent = data;
      });
  </script>

Network error thrown in the Console:

Access to fetch at 'https://new-express-project-p61e9hmrr-wedothebest4yous-projects.vercel.app/' from origin 'http://localhost:2000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.Understand this error
(index):15 
       
GET https://new-express-project-p61e9hmrr-wedothebest4yous-projects.vercel.app/ net::ERR_FAILED 401 (Unauthorized)
(anonymous) @ (index):15Understand this error
(index):15 
        
Uncaught (in promise) TypeError: Failed to fetch
at (index):15:5
(anonymous) @ (index):15
Promise.then
(anonymous) @ (index):25Understand this error

Have you tried adding the headers in your Express configuration instead of a vercel.json file?

You can see an example of that discussed here: javascript - Express JS: No 'Access-Control-Allow-Origin' header is present on the requested resource - Stack Overflow

Express CORS Middleware is another option that might make configuration easier for you.

Thank you for your time and the suggestions.

Earlier on I had followed the docs over here : How can I enable CORS on Vercel?. The third option is the one which I have been trying since the first and second cases are not mine. Does it mean that this third option will not work, or the way in which I tried is not correct, or it is not currently the recommended way.

Anyways, I have followed the two options you now have suggested, and the feedback enclosed below. The status is the same issue still persists.

Option 1 :

You can see an example of that discussed here: javascript - Express JS: No ‘Access-Control-Allow-Origin’ header is present on the requested resource - Stack Overflow

Update references :

Inspect: https://vercel.com/wedothebest4yous-projects/new-express-project/DTcKfVyN42B4zyhWFQrPuXkYQBnt [3s]
Preview: https://new-express-project-1efbmmk4s-wedothebest4yous-projects.vercel.app 
CORS : Used the URL for CORS

Test run 1 :

Result expected : done
Result received : Network error as shown below.
Status : The CORS issue reported originally still persists.
Access to fetch at 'https://new-express-project-1efbmmk4s-wedothebest4yous-projects.vercel.app/' from origin 'http://localhost:2000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.Understand this error
(index):15 
        
GET https://new-express-project-1efbmmk4s-wedothebest4yous-projects.vercel.app/ net::ERR_FAILED 401 (Unauthorized)
(anonymous) @ (index):15Understand this error
(index):15 

Uncaught (in promise) TypeError: Failed to fetch at (index):15:5
(anonymous) @ (index):15
Promise.then
(anonymous) @ (index):25Understand this error

Option 2:

Express CORS Middleware is another option that might make configuration easier for you.

Update references:

Inspect: https://vercel.com/wedothebest4yous-projects/new-express-project/9NsL7jVqa1mcB4X2BS1vH5sLuEdD [3s]
Preview: https://new-express-project-lxo25p9y1-wedothebest4yous-projects.vercel.app
CORS : Used the URL for CORS

Test run 2

Result expected : done
Result received : Network error as shown below.
Status : The CORS issue reported originally still persists.
Access to fetch at 'https://new-express-project-lxo25p9y1-wedothebest4yous-projects.vercel.app/' from origin 'http://localhost:2000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.Understand this error
new-express-project-lxo25p9y1-wedothebest4yous-projects.vercel.app/:1 
        
Failed to load resource: net::ERR_FAILEDUnderstand this error
(index):15 
       
Uncaught (in promise) TypeError: Failed to fetch at (index):15:5

The third option from that guide could work. But it’s best to use the framework’s preferred strategy when one is provided since this prevents configuration conflicts. I’d recommend configuring it the “Express” way for your project.

I found some additional tips that could help in your case:

Are you able to check which headers are actually being applied? If the headers are missing, then you know that’s the problem. If the headers are present, then something else is causing the error.

It’s also worth reading to understand more about CORS. That can help you understand how it works so you can identify what’s going wrong.

Thank you for the additional information, I shall take a look.

Now on to this case:

Are you able to check which headers are actually being applied?

The server console output generated just before res.send shows the following origin. This is correct as per the CORS setting.

Access-Control-Allow-Origin : http://localhost:2000

However, the response header at the Browser, does not show the same. The full list of response headers shown below.

Notably the following warning is displayed against the set-cookie header as well.

Response headers

cache-control: no-store, max-age=0

content-length: 13123

content-type:  text/html; charset=utf-8

date: Tue, 13 Aug 2024 07:45:34 GMT

server: Vercel

set-cookie: _vercel_sso_nonce=bkCzjwUJ6oqKqKvTeWqvkeun; Max-Age=3600; Path=/; Secure; HttpOnly; SameSite=Lax

strict-transport-security: max-age=63072000; includeSubDomains; preload

x-frame-options: DENY

x-robots-tag: noindex

x-vercel-id: bom1::42tkq-1723535134454-6e2f7aac5b2d

Hello, Will there by anymore help I may receive ?

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.