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


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

  • 相关阅读:
    opensuse字符和图形界面
    Eclipse编辑器小手段
    切换运行时用户以及用户组
    PHP安装和配置
    Linux程序资源限制简述
    test2234343
    找回Svn和Git不见的文件图标
    SourceInsight使用技巧
    Javascript数组使用方法
    MySQL安装和配置
  • 原文地址:https://www.cnblogs.com/yszr/p/10468546.html
Copyright © 2020-2023  润新知