请教一个跨域的问题: No 'Access-Control-Allow-Origin' header ,参考了很多教程还是解决不了。

2017-03-27 20:52:29 +08:00
 kmdd33
参考的教程如下: http://serverfault.com/questions/162429/how-do-i-add-access-control-allow-origin-in-nginxhttp://www.tuicool.com/articles/3aaQB3bhttps://segmentfault.com/q/1010000003116113

自己尝试在 nginx.conf 文件中添加了
location / {
add_header Access-Control-Allow-Origin *;
}





location / {
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
#
# Om nom nom cookies
#
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
#
# Custom headers and headers various browsers *should* be OK with but aren't
#
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
#
# Tell client that this pre-flight info is valid for 20 days
#
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
if ($request_method = 'POST') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}
if ($request_method = 'GET') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}
}

丝毫不起作用,求助后端伙伴们,怎么搞?
console 里面的错误(不知道如何贴图,就只能贴 error 了)如下:

XMLHttpRequest cannot load https://www.mydomain.com/?/ac... No 'Access-Control-Allow-Origin' header is present on the https://www.mydomain.com/?/ac... requested resource. Origin 'https://www.mydomain.com' is therefore not allowed access.
27295 次点击
所在节点    问与答
43 条回复
qinxi
2017-03-28 23:09:12 +08:00
@kmdd33 你的页面在 a.com ,你的 api 在 b.com 那你在 a.com/api 反向代理到 b.com 就行了 .
030
2017-03-29 03:24:16 +08:00
我前几天换 CloudFront 也碰到过这个,不过加了
add_header Access-Control-Allow-Origin *;
就好了,问题只是 CloudFront 会把 header cache ,好像和主题沒什么关系
cst4you
2017-03-29 10:37:54 +08:00
@qinxi 如果是多媒体类的资源文件你还反代来消耗自己流量吗 233333333

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://tanronggui.xyz/t/350723

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX