Ad

Http Request To A Local Node Server From Local Angular Project CORS ERR

- 1 answer

I am making a local project, I use angular 6 form that run on node server localhost:4200/ and nodeJs that run on node server but at different port localhost:2000

The problem is getting CORS security error even though I prepared the nodejs to accept the request.

Angular Code

  register(regData){
    return this.httpClient.post(this.url,regData);
  }

npm install cors --save // intsall cors (NodeJs)

NodeJs

const express  = require('express')
,cors = require('cors')
,app = express();
var bodyParser = require('body-parser');

const productR = require('./routes/product');

// middleware
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());

var originsWhitelist = [
    'http://localhost:4200',      //this is my front-end url for development
    'http://127.0.0.1:4200'
  ];
  var corsOptions = {
    origin: function(origin, callback){
          var isWhitelisted = originsWhitelist.indexOf(origin) !== -1;
          callback(null, isWhitelisted);
    },
    credentials:true
  }
  app.use(cors(corsOptions));
  app.use('/products', productR);

ERROR MESSAGE

Access to XMLHttpRequest at 'localhost:2000/products/create' 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, https.

Ad

Answer

This error message means that the URL which you use for requests from the client-side contains incorrect protocol. In your case, there was no protocol in the URL at all.

So, the solution of your problem is to use http://localhost:2000 instead of localhost:2000.

The protocol is an important part of the URL because there are big differences between the protocols. For example, your URL could look like file:///localhost... or ftp://localhost... and so on. So it will be better to always define it directly.

Ad
source: stackoverflow.com
Ad