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

後端放行這個請求頭後端

相關文章
相關標籤/搜索