Access to XMLHttpRequest at 'http://localhost:3000/' from origin 'http://192.168.X.X:XX' has been blocked by CORS policy [duplicate]

和自甴很熟 提交于 2019-12-25 18:34:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!