Node-③ koa 框架搭建的后台中如何允许前端进行跨域请求

1.遇到跨域阻止ERR 时
   Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
   from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

1. 在后台的app.js(或者你自己命名的入口文件如server.js等)中,添加一个允许跨域请求头的设置即可 

// 设置跨域
app.use(async (ctx, next) => {
  ctx.set('Access-Control-Allow-Origin', '*');
  await next();
});
方案二:争对传参的设置
app.use(async (ctx, next) => {
  ctx.set('Access-Control-Allow-Origin', '*');
  ctx.set('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type');
  ctx.set('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS');
  await next();
});
 
2. 前端设置请求模式为跨域。
   
function TryLogin() {
this.axios.post(`http://10.244.4.4:3001/FixedAssetsManagement/Api/RegisteredAccount`, " ", {
mode: "cors",
headers: {
'Accept': 'application/json,text/plain,*/*'
}
}).then(function(response) {
console.log(response);
const data = response.data;
}, function(response) {});

posted on 2020-12-10 16:47  月星辰帝子兮  阅读(325)  评论(0)    收藏  举报

导航