axios+koa 开发小记

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

clipboard.png

解决方法:axios

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

后端放行这个请求头后端

相关文章
相关标签/搜索