1

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.

2
  • 2
    Have you tried to change the url to http://localhost:2000 (instead of localhost:2000) in your client-side code? Make sure that this.url (in this.httpClient.post(this.url,regData);) starts with http://... Commented Jan 19, 2019 at 11:13
  • @MaxMartynov thank you, this solved my problem Commented Jan 19, 2019 at 17:24

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.