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

本文介绍了一种解决跨域请求问题的方法,通过使用Nginx作为代理服务器,实现前端页面与后端接口的数据交互。文章详细展示了如何配置Nginx,并通过实例演示了如何设置前端代码以正确调用后端API。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

引入网址https://blog.youkuaiyun.com/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 文件,可以看到,跨域请求,成功访问数据 

转载于:https://www.cnblogs.com/yszr/p/10468546.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值