对于这样的代码,我们执行以后,浏览器端访问会报跨域错误:
方案一:手动解决
// 设置允许跨域访问该服务
app.all('*',function(req,res,next){
res.header("Access-Control-Allow-Origin","*");
res.header("Access-Control-Allow-Methods","PUT,GET,POST,DELETE,OPTIONS");
res.header("Access-Control-Allow-Headers","X-Requestd-With");
res.header("Access-Control-Allow-Headers","Content-Type");
next()
});
注意解决跨域的代码要放在处理路由的代之前,否则将会不起作用,这样就可以解决跨域问题,还能直接本地打开访问页面
方案二:第三方包cors
npm i cors --save