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预检请求,如果后端没有对应的设置响应头,将无法通过而报出以上错误。

clipboard.png

解决方法:

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()
})

后端放行这个请求头


AwesomeHan
125 声望4 粉丝

引用和评论

0 条评论