I'm trying to send a POST
request to my Express
server, but it always throws this error
Access to fetch at 'http://localhost:4000/users/sign-up' from origin 'http://localhost:3000' 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.
And this is how I setup my server "using TypeScript"
import express, { Application } from 'express';
import * as dotenv from 'dotenv';
import { databaseConnect, serverConnect } from './modules/connections';
import bodyParser from 'body-parser';
import cors from 'cors';
import devicesRouter from './routes/dashboard';
import usersRouter from './routes/users';
import announcementsRouter from './routes/announcements';
import ordersRouter from './routes/orders';
// Initializing express
const app: Application = express();
// Server configurations
dotenv.config();
await databaseConnect();
app.use(express.json());
app.use(bodyParser.json());
app.use(cors({ origin: "http://localhost:3000", credentials: true }));
// Defining server routes
app.use('/devices', devicesRouter);
app.use('/users', usersRouter);
app.use('/announcements', announcementsRouter);
app.use('/orders', ordersRouter);
// Connecting server
serverConnect();
And in my client I'm using the fetch API
to send the post request
const response = await fetch("http://localhost:4000/users/sign-up", { method: "POST", headers: { "Accept": "application/json", "Content-Type": "application/json", "Access-Control-Allow-Origin": "http://localhost:3000" }, body: JSON.stringify(signUpData) });
I have seen many videos about fixing this error just by installing the cors
package, but somehow it didn't work for me.
I tried to reinstall both the cors
and @types/cors
packages but nothing changes.
I also tried using
app.use(cors({ origin: "http://192.168.1.3:3000", credentials: true }));
instead of
app.use(cors({ origin: "http://localhost:3000", credentials: true }));
but it did't work as well.