0

I am getting the following error while calling http get from angular component:

"Failed to load http://localhost:3005/json: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.".

2 Answers2

0

You need to set header to allow access from localhost in router of (express) Node.js . Below code where I have use * to node server to access request from all sources.

router.use(function(req,res,next){
    res.header('Access-Control-Allow-Origin', req.get('Origin') || '*');
    res.header('Access-Control-Allow-Credentials', 'true');
    res.header('Access-Control-Allow-Methods', 'GET,HEAD,PUT,PATCH,POST,DELETE');
    res.header('Access-Control-Expose-Headers', 'Content-Length');
    res.header('Access-Control-Allow-Headers', 'Accept, Authorization, Content-Type, X-Requested-With, Range');
    next();
});
Saurabh Lende
  • 953
  • 2
  • 13
  • 19
0

An easier fix to that is to use express middleware cors.

This will (kind-of) add the above settings for you so you can forget about those. It is very important that you only enable this in dev mode as this could result in serious security issues. Consider doing something like:

const server = require('express')();
const cors = require('cors');
if (isDevelopmentMode) {
    server.use(cors());
}
Wayrex
  • 2,027
  • 1
  • 14
  • 25