[▲ Vercel Community](/) · [Categories](/categories) · [Latest](/latest) · [Top](/top) · [Live](/live)

[Help](/c/help/9)

# CORS issue

353 views · 1 like · 9 posts


Wedothebest4you (@wedothebest4you) · 2024-08-05

**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** : https://vercel.com/guides/how-to-enable-cors

Request your valuable help.
WeDotheBest4You.


Amy Egan (@amyegan) · 2024-08-05 · ♥ 1

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](https://vercel.com/guides/creating-a-minimal-reproducible-example) is usually the fastest way to let others see what you see so we can help you debug the problem.


Wedothebest4you (@wedothebest4you) · 2024-08-09

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


Wedothebest4you (@wedothebest4you) · 2024-08-09

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
```


Amy Egan (@amyegan) · 2024-08-09

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: https://stackoverflow.com/a/40026625

[Express CORS Middleware](https://expressjs.com/en/resources/middleware/cors.html) is another option that might make configuration easier for you.


Wedothebest4you (@wedothebest4you) · 2024-08-10

Thank you for your time and the suggestions.

Earlier on I had followed the docs over here : https://vercel.com/guides/how-to-enable-cors. 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](https://stackoverflow.com/a/40026625)

```
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](https://expressjs.com/en/resources/middleware/cors.html) 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
```


Amy Egan (@amyegan) · 2024-08-12

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:
- [Configure the CORS stuff **before** your routes](https://stackoverflow.com/a/34647929)
- [Handle the HTTP OPTIONS method before handling other request methods on the same route](https://stackoverflow.com/a/34647991)
- [Pass "http://" before "localhost:"](https://stackoverflow.com/a/56051528)

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.
- https://developer.mozilla.org/en-US/docs/Glossary/CORS
- https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request


Wedothebest4you (@wedothebest4you) · 2024-08-13

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.**

**![|260x136](upload://evFpoHR2qILntO8RDU2RVfSErqx.png)**

**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
```


Wedothebest4you (@wedothebest4you) · 2024-08-15

Hello, Will there by anymore help I may receive ?