问题
Trying to access Node server (http://localhost:3000)
from Angular 7 (http://192.168.X.X)
Set CORS i.e.
this.app.use(cors())
this.app.use(bodyParser.json())
this.app.use(bodyParser.urlencoded({ extended: false }))
but getting
Access to XMLHttpRequest at 'http://localhost:3000/' from origin 'http://192.168.X.X:XX' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Tried this middleware function
this.app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Origin', 'http://192.168.X.X:4200');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
but all in vain. Any help or suggestion that could resolve my issue???
Update
When hosted my Angular
app to Heroku
, it works fine but on local ip it gives CORS
error.
Tried as
this.app.use(cors())
this.app.options('*', cors())
but still no luck
回答1:
Try adding these two
app.options("/*", function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
res.sendStatus(200);
});
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
next();
});
来源:https://stackoverflow.com/questions/55254354/access-to-xmlhttprequest-at-http-localhost3000-from-origin-http-192-168