CORS Policy problem when I try to connect from Angular to Nodejs backend [duplicate]

  angular, cors, node.js

I´m trying to develop a backend basic server in NodeJS and the front in Angular 11, the fact is when I try to make a http get request to the backend, this is the error message in console:

Access to XMLHttpRequest at 'localhost:3000/api/personas' from origin 'http://localhost:4200' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.

I´ve tried to config a reverse proxy in angular like this:

proxy.conf.json

{
"/localhost:3000*": {
    "target": "http://localhost:3000",
    "secure": false,
    "logLevel": "debug"
  }
}

And the backend is set like this:

index.js (nodejs backend)

const express = require('express');
const path = require('path');
const methodOverride = require('method-override');
const cors = require('cors');

// Initialitations

const app = express();
require('./database');

// Settings

app.set('port', process.env.PORT || 3000);

// Middlewares

app.use(cors({
    origin: 'http://localhost:4200'
}));
app.use(express.urlencoded({ extended: false }));
app.use(methodOverride('_method'));

// Global variables

// Routes

app.use('/api', require('./routes/persona'));

// Static files

app.use(express.static(path.join(__dirname, 'public')));

// Server init

app.listen(app.get('port'), () => {
    console.log('Server on port: ', app.get('port'));
})

Source: Angular Questions

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.