sorry for the repeated question but I'm stuck at it.
CORS issue is not getting resolved from any of my code. I tried many possible ways to solve CORS issue but it didn't.
const app = express();
// Middlewares
app.use(express.json());
app.use(morgan('dev'));
// Access-Control-Allow-Origin
/* app.options('*', cors());
app.use(cors()); */
app.use('*', (req, res, next) => {
// console.log({ message: 'in middleware' });
/* req.headers['Access-Control-Allow-Origin'] = 'http://localhost:3000';
req.headers['Access-Control-Allow-Methods'] = 'GET,PUT,POST,DELETE,OPTIONS';
req.headers['Access-Control-Allow-Headers'] =
'Content-Type, Accept, Access-Control-Allow-Origin, Authorization'; */
console.log({ headers: req.headers });
next();
});
var corsOptions = {
origin: 'http://localhost:5000/api/v1/',
optionsSuccessStatus: 200,
};
// API routes
app.get('/api/v1/', (req, res) =>
res.status(200).json({ message: "Welcome to the Radical's API" })
);
As you can see, I tried multiple ways to solve it, research about it as much as possible, but it's not get solved then I commented. After trying every possible way, now I'm here to present my situation.
Please help me.
CodePudding user response:
Just add this code in your response and I hope it will work
res.header("Access-Control-Allow-Origin", "*");
CodePudding user response:
Configure cors for your node js app, in origin insert frontend server url.
var corsOptions = {
origin: 'http://localhost:3000',
optionsSuccessStatus: 200
}
app.use(cors(corsOptions));
(insert this code after app.use(morgan('dev'));)
CodePudding user response:
There is a nodejs package called cors. You can use this.
npm install cors
const cors = require("cors");
app.use(cors({
origin: '*'
}));