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