Currently, I am working on developing a web application and an API simultaneously, but I'm facing some issues with CORS blocking. This concept is relatively new to me, and I'm eager to improve my understanding.
Firstly, I have set up an Express server for the API:
const express = require('express')
const cors = require('cors')
const app = express()
module.exports = app.post('/posttest/', cors(), async (req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.json({ msg: 'Successfully tested with CORS!' })
})
This server is running locally on http://localhost:3000 The "posttest" mentioned above refers to the module that handles my route.
const posttest = require('./src/routes/posttest.js')
const server = require('http').createServer();
const { Router } = require('express');
server
.on(
'request',
Router({ mergeParams: true })
.use( posttest )
)
.on('listening', () =>{
console.log('listening');
})
.on('error', () => {
console.log('ERROR!!!!');
})
.listen(3000);
Next, in my web application, I make a POST request using fetch:
fetch('http://localhost:3000/posttest/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({text:'test'}),
mode: 'cors' }) .then( (res) => { //resolve }) .catch( (err) => { //error });
It's worth mentioning that the web app is served locally on localhost:8080
The issue arises when attempting to make a post request as it results in the following error:
Error: Access to fetch at 'http://localhost:3000/posttest/' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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.
I primarily use Chrome for development. Any suggestions on why this is happening? I was under the impression that including
res.header('Access-Control-Allow-Origin', '*');
would resolve the issue. Interestingly, Postman can access the route successfully. However, when accessing the same route through a browser, it gets denied. The same problem persists during production deployment. Can someone provide a simple explanation, perhaps suitable for a five-year-old?
Thank you in advance for your assistance.