问题复现:java两个项目A,B,启动后A中ajax调用B中的方法获取数据,遇到的跨域问题nginx方式处理。(问题解决注意要点:要以代理的方式启动A才行)
服务A调用服务B
服务A的端口号:8080
这里的ajax请求服务B中的方法
/**
* 第二种方式,使用nginx来处理
* ,{emulateJSON:true}
**/
this.$http.post("http://localhost:8888/testCrossDomainNginx2Vue").then(function (data) {
//通过data.body的形式来拿到服务器返回成功的数据
this.id=data.body.id;
this.name=data.body.name;
this.age=data.body.age;
})
服务B的端口号:8088
//测试nginx方式
@PostMapping("/testCrossDomainNginx2Vue")
@ResponseBody
public String testCrossDomainNginx2Vue(HttpServletRequest request){
System.out.println("进入到nginx跨域服务器中了");
Student student=new Student("A001","zs","23");
return JSON.toJSONString(student);
}
因为这里是两个服务都启动了,不是静态页面调用其他服务,只是静态页面调用的话不用代理服务A,但是这里需要,nginx的配置如下:
upstream tomcatserver1 {
server 127.0.0.1:8080;
}
upstream tomcatserver2 {
server 127.0.0.1:8088;
}
server {
listen 8888;
server_name localhost;
location / {
proxy_pass http://tomcatserver1;
index index.html index.htm;
}
location /testCrossDomainNginx2Vue {
proxy_pass http://tomcatserver2;
}
}
这里我我们登陆服务A,不能直接输入
http://localhost:8080/vue/crossDomain
要改成
http://localhost:8888/vue/crossDomain
ajax中的链接如下
http://localhost:8888/testCrossDomainNginx2Vue
这样处理,服务A和A中的链接就是同源情况了