I know this is an usual issue and there are many solutions, however I tried everything and nothing has changed at all. I deployed node and postgresql on Heroku to have a Rest API and fetch it from Angular with HttpClient. I have already deployed it and everything works fine with Postman, however in browser, it shows me this error:
Access to XMLHttpRequest at 'https://myapi.herokuapp.com/products/' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
This is my node app:
const express = require('express');
const cors = require('cors');
const app = express();
//MiddleWares
app.use(express.json());
app.use(express.urlencoded({extended:false}));
//Router:
app.use(require('./routes/index'));
const PORT = process.env.PORT || 4000;
const corsOptions = {origin: process.env.URL || '*', credentials: true};
app.use(cors(corsOptions));
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*")
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested, Content-Type, Accept Authorization"
)
if (req.method === "OPTIONS") {
res.header(
"Access-Control-Allow-Methods",
"POST, PUT, PATCH, GET, DELETE"
)
return res.status(200).json({})
}
next()
});
app.listen(PORT, err => {
if(err) throw err;
console.log('Server on port 4000');
});
This is my package.json:
{
"name": "backend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node src/index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.18.1",
"pg": "^8.7.3"
},
"devDependencies": {
"nodemon": "^2.0.16"
}
}
And Angular:
constructor(
private http: HttpClient
) { }
getAllProducts() {
return this.http.get<Product[]>(`${environment.url_api}/products/`);
}
A browser extension won't help since I will need to deploy the Angular project on a hosting
CodePudding user response:
Thanks for the comments, I already resolved it by removing the cors package and only having a bunch of code for the cors configuration. My node app ended on this:
const express = require('express');
const app = express();
//Cors Configuration - Start
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*")
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested, Content-Type, Accept Authorization"
)
if (req.method === "OPTIONS") {
res.header(
"Access-Control-Allow-Methods",
"POST, PUT, PATCH, GET, DELETE"
)
return res.status(200).json({})
}
next()
})
//Cors Configuration - End
//Router:
app.use(require('./routes/index'));
const PORT = process.env.PORT || 4000;
app.listen(PORT, err => {
if(err) throw err;
console.log('Server on port 4000');
});
As you can see, I didn't use the cors npm package. : I got it from this blog https://medium.com/nerd-for-tech/solving-cors-errors-associated-with-deploying-a-node-js-postgresql-api-to-heroku-1afd94964676/