Access to XMLHttpRequest has been blocked by CORS policy: Request header field l

HAcSeeking 2018-11-05

问题报错:

Access to XMLHttpRequest at 'http://localhost:3030/api/asset-list' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field lang is not allowed by Access-Control-Allow-Headers in preflight response.

问题解析:

前端服务器fetch.js请求后端服务器api报跨域问题

前端服务器:3000,后端服务器:3030,KOA2

由于前端请求的header字段未在服务器端运行,导致请求跨域报错。

解决方案:

在后端response返回的header允许前端header的请求

以koa2为例:

router.all('*', (ctx, next) => {
  // 允许来自所有域名请求
  ctx.set('Access-Control-Allow-Origin', '*');

  // 是否允许发送Cookie,ture为运行
  ctx.set('Access-Control-Allow-Credentials', true);

  // 设置所允许的HTTP请求方法
  ctx.set('Access-Control-Allow-Methods', 'OPTIONS, GET, PUT, POST, DELETE');

  // 服务器支持的所有头信息字段,多个字段用逗号分隔
  ctx.set('Access-Control-Allow-Headers', 'x-requested-with, x-ui-request, lang');
  next();
});

相关推荐

张立军的架构之路 / 0评论 2017-12-28