本地写的Node.js服务,postman调接口可以调通,但是当我本地使用axios调接口的时候却出现跨域问题
Access to XMLHttpRequest at ‘http://localhost:3000/stu’ from origin ‘http://127.0.0.1:5500’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
F12查看network报错 [CORS error]
上面是报错信息,下面是浏览器F12提示的报错
调接口很多次了,当看到console中报错有这个字段**[‘Access-Control-Allow-Origin’]**的时候,就应该知道是跨域问题了,解决办法就是在res返回数据时加上下面代码即可完美解决
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By", ' 3.2.1')
res.header("Content-Type", "application/json;charset=utf-8");
next();
});
其实最重要的代码是第一句res.header("Access-Control-Allow-Origin", "*");
加上这句 完美解决本地跨域问题
最后是效果图可以正常访问本地服务器的接口