axioskoa-开发小记

33次阅读

共计 524 个字符,预计需要花费 2 分钟才能阅读完成。

Access to XMLHttpRequest at ‘http://localhost:8888/’ from origin ‘http://localhost:8080’ has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.

axios 如果携带着 data 参数发送请求,会添加一个自定义请求头:Access-Control-Request-Headers: content-type,在发送正式请求前会发送 OPTIONS 预检请求,如果后端没有对应的设置响应头,将无法通过而报出以上错误。

解决方法:

server.use(async (ctx, next) => {console.log(`visited PATH: ${chalk.blue(ctx.path)}`)
  ctx.set({
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Headers': 'Content-Type'
  })
  await next()})

后端放行这个请求头

正文完
 0