引入網址https://blog.csdn.net/larger5/article/details/81286324
1、請求后端數據失敗
代碼:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <script type="text/javascript" src="https://code.jquery.com/jquery-3.1.0.min.js"></script> <script type="text/javascript"> function upd() { $.ajax({ type: "get", url: "http://120.79.197.130:8530/spring/user/get", success: function(result) { console.log(result); } }); } </script> <body> <!--獲取--> <button id="btn2" onclick="upd()">Get request 獲取</button> </body> </html>
2、加入 nginx
nginx 的下載方法:nginx: download
1、在 conf/nginx.conf 中,很多都是默認配置,筆者把注釋去掉,添加了自己少量的配置
worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; server { listen 8888; # 任意 server_name localhost; location / { root html; index index.html index.htm; } # 新加的 location /spring { proxy_pass http://120.79.197.130:8530; # 后端接口 IP:port } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } }
2、點擊 開啟服務
3、修改代碼上述 html 代碼的 url
$.ajax({
type: "get",
url: "/spring/user/get", // 注意鏈接
success: function(result) {
console.log(result);
}
});
4、將代碼文件放入 nginx 的 html 文件夾中(可以把里邊的其他 html 刪掉)
如下
5、基於 nginx 服務器,訪問該 html 文件,可以看到,跨域請求,成功訪問數據