完整问题复现如下:
已拦截跨源请求:同源策略禁止读取位于XXXXXXXXXXXXXXXX/demo_test.txt 的远程资源。(原因:CORS 请求不是 http)
原始代码index.html在附录中
##############################################################################################
解决方案:
概念上:
CORS请求和HTTP请求不是一个东西。
CORS请求的协议是CORS
HTTP请求的协议是HTTP
1./home/appleyuchi/load_test下面放置demo_test.txt和index.html(html中的代码不需要修改)
demo_test.txt里面的内容是:
"这里是输出的内容"
2.
nginx -c /etc/nginx/nginx.conf(该文件在文末附录中)
nginx -s reload
3.
浏览器打开
http://127.0.0.1:10072/load_test/
点击
############################附录##################################################################
/etc/nginx/nginx.conf
user root;
worker_processes 2;
error_log /usr/local/nginx/error.log;
pid /usr/local/nginx/nginx.pid;
events {
worker_connections 1024;
}
http {
include /usr/local/nginx/conf/mime.types;
default_type application/octet-stream;
server {
listen 10072;
server_name localhost;
access_log /var/log/nginx/access.log;
#配置跨域
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Headers X-Requested-With;
add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
location / {
root /home/appleyuchi;
autoindex on;
#proxy_pass http://127.0.0.1:10071;
#proxy_set_header Host $host;
#proxy_set_header X-Real-IP $remote_addr;
#proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
}
/home/appleyuchi/index.html如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").load("demo_test.txt");
});
});
</script>
</head>
<body>
<div id="div1"><h2>使用 jQuery AJAX 修改文本内容</h2></div>
<button>获取外部内容</button>
</body>
</html>
来源:CSDN
作者:东方朔盗仙桃
链接:https://blog.csdn.net/appleyuchi/article/details/103649145