什么是跨域?

使用js获取数据时,涉及到的两个url只要协议、域名、端口有任何一个不同,都被当作是不同的域,相互访问就会有跨域问题。
例如客户端的域名是back2me.cn,而请求的域名是font.back2me.cn
如果直接使用ajax访问,会有以下错误


XMLHttpRequest cannot load https://back2me.cn/server.php. No 'Access-Control-Allow-Origin' header is present on the requested resource.Origin 'https://back2me.cn' is therefore not allowed access.

如何解决跨域?

在nginx配置文件中加入下面三行即可。

add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
最后修改:2022 年 12 月 12 日
如果觉得我的文章对你有用,请随意赞赏