跨域请求时经常遇到 https://github.com/axios/axios/issues/569 这种问题:
CORS error No 'Access-Control-Allow-Origin' header is present on the requested resource
这是由于所请求的跨域资源返回的header里的Access-Control-Allow-Origin
未包含当前所在域,如果跨域资源的后端服务是藏在nginx后面,只需要在对应的位置加上
add_header 'Access-Control-Allow-Origin' 'http://example.com'
就行了。
但如果是用koa直接提供的后端服务,比如一个post请求,你光在router.post里加上header还是不一定行:
router.post('/some-url', ctx => {
ctx.set('Access-Control-Allow-Methods', 'GET,POST,OPTIONS')
ctx.set('Access-Control-Allow-Origin', ctx.request.header.origin)
ctx.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-type')
...
}
这是因为浏览器如果发现要请求的资源跨域了的话,它会先发一个option请求去拿对应资源的header,如果header不包含Access-Control-Allow-Origin
的话就直接抛跨域错误了。。所以还得再加一个router:
router.options('/some-url', ctx => {
ctx.set({
'Allow': 'OPTIONS,GET,HEAD,POST',
'Access-Control-Allow-Methods': 'GET,POST,OPTIONS',
'Access-Control-Allow-Origin': ctx.request.header.origin,
'Access-Control-Allow-Headers': 'X-Requested-With, Content-type'
})
ctx.status = 204
})