首页 > 其他 > 详细

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

时间:2019-03-04 00:27:17      阅读:203      评论:0      收藏:0      [点我收藏+]

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

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

原文:https://www.cnblogs.com/yszr/p/10468546.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!