前端使用 Nginx 反向代理彻底解决跨域问题

时间:2023-03-09 04:57:43
前端使用 Nginx 反向代理彻底解决跨域问题

引入网址https://blog.****.net/larger5/article/details/81286324

1、请求后端数据失败

前端使用 Nginx 反向代理彻底解决跨域问题

代码:

<!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 前端使用 Nginx 反向代理彻底解决跨域问题

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、点击 前端使用 Nginx 反向代理彻底解决跨域问题开启服务 
3、修改代码上述 html 代码的 url

$.ajax({
type: "get",
url: "/spring/user/get", // 注意链接
success: function(result) {
console.log(result);
}
});
4、将代码文件放入 nginx 的 html 文件夹中(可以把里边的其他 html 删掉)

前端使用 Nginx 反向代理彻底解决跨域问题

如下

前端使用 Nginx 反向代理彻底解决跨域问题

5、基于 nginx 服务器,访问该 html 文件,可以看到,跨域请求,成功访问数据 前端使用 Nginx 反向代理彻底解决跨域问题