Nginx前后端分离解决跨越

一、什么是跨域?

跨域指的是浏览器不能执行其它网站的脚本,它是由浏览器的同源策略造成的,是浏览器对JavaScript 施加的安全限制。

二、同源策略

根据百度百科 同源策略它是由 Netscape 提出的一个安全策略,它是浏览器最核心也是最基本的安全功能,如果缺少同源策略,则浏览器的正常功能可能都会受到影响,现在所有支持JavaScript的浏览器都会使用这个策略。

所谓同源指的是:协议、域名、端口号都相同,只要有一个不相同,那么都是非同源。

同源策略限制的情况:

  1、Cookie、LocalStorage 和 IndexDB 无法读取

  2、DOM 和 Js对象无法获得

  3、AJAX 请求不能发送

  注意:对于像 img、iframe、linked、script 等标签的 src 属性是特例,它们是可以访问非同源网站的资源的。

三、如何解决跨域

1、response 添加header。

扫描二维码关注公众号,回复: 7183071 查看本文章

2、JSONP 方式。

3、HttpClient 请求转发。

4、nginx 转发

5、其他更多...

具体解决方案可参考大神的文章:https://www.cnblogs.com/ysocean/p/9380551.html

四、nginx解决跨越

问题描述:使用nginx发布前端内容,使用tomcat发布后端内容,会出现跨越问题。

1、前端项目放在myhtml下,使用nginx发布该项目。

server {
        listen       8888;
        server_name  localhost;
        location / {
        #静态服务器
            root   /Users/David/myhtml;
            index  index.html index.htm;
        }
}

2、后端项目使用tomcat发布,tomcat端口号为8080。

@RestController
public class UserController {
    @Autowired
    UserService userService;

    @RequestMapping("/get")
    public List<User> getUserByPage(int pageSize, int pageNum){
        List<User> userList = userService.getAllUser();
        return userList;
    }
}

3、前端页面show.html访问后端ajax代码:

$.ajax({
         url: "http://localhost:8080/get",
         type: "post",
         dataType: "json",
         success: function (data) {
         console.log(data);
         }
});

 ❌ 此时数据无法发正常获取,因为违反了同源策略

解决方案:使用nginx代理tomcat容器,定义html访问规则和tomcat转发规则,实现html内容和tomcat内容都由nginx代理。解决跨域问题。

1、前端项目放在myhtml下,使用nginx发布该项目,定义访问规则。

#静态服务器
location ~.(html|js|css) {
    root   /Users/David/myhtml;
    index  index.html index.htm;
}

2、后端项目使用tomcat发布,tomcat端口号为8080,修改controller添加虚拟路径。

@RestController
@RequestMapping("/spring")
public class UserController {
    @Autowired
    UserService userService;

    @RequestMapping("/get")
    public List<User> getUserByPage(int pageSize, int pageNum){
        List<User> userList = userService.getAllUser();
        return userList;
    }
}

3、添加nginx代理tomcat服务代码,此时访问:http://localhost:8888 可以转发到:http://localhost:8080

location ~/spring {
    #反向代理
    proxy_pass http://localhost:8080;
}

4、修改前端ajax代码

$.ajax({
         url: "http://localhost:8888/spring/get",
         type: "post",
         dataType: "json",
         success: function (data) {
         console.log(data);
         }
});

✔️此时可以正常访问数据。

nginx核心配置:

server {
    listen       8888;
    server_name  localhost;
    #静态服务器
    location ~.(html|js|css) {
        root   /Users/David/myhtml;
        index  index.html index.htm;
    }
    #反向代理tomcat
    location ~/spring {
        proxy_pass http://localhost:8080;
    }
}

解析:

  前端页面的访问地址为:http://localhost:8888/show.html

  show.html页面中请求后端地址为:http://localhost:8888/spring/get (此时不违反跨越提交的规范,同域正常提交请求。)

  后端地址符合nginx转发规则,代理转发到地址:http://localhost:8080/spring/get(可以正常取到数据)   

参考大神文章:

https://www.cnblogs.com/ysocean/p/9380551.html

猜你喜欢

转载自www.cnblogs.com/david1216/p/11466123.html