I am working on an Angular app with NodeJs backend and I am getting CORS error even after using CORS middleware. Have a look at my code:
var mysql = require('mysql');
const fs = require('fs');
const express = require('express');
const app = express();
const cors = require('cors');
let corsOptions = {
origin: ['http://localhost:4200', 'localhost:4200'],
}
app.use(cors(corsOptions));
var bodyParser = require('body-parser');
const bcrypt = require('bcrypt');
const saltRounds = 10;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.post('/login', (req, res) => {
//Code
});
Here is the error on Chrome:
Access to XMLHttpRequest at 'localhost:8088/login' from origin 'http://localhost:4200' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, isolated-app, chrome-extension, chrome, https, chrome-untrusted.
auth.service.ts:16
POST localhost:8088/login net::ERR_FAILED
How do I solve this CORS error now let me now please!
The code you provided has an issue with the origin URLs specified in the corsOptions object. The origins should include the scheme (e.g., "http://") but they are missing it. To fix the CORS error, update the corsOptions object like this:
This change ensures that the CORS middleware works correctly, allowing your Angular app to communicate with the Node.js backend without encountering CORS errors.