在做web开发的时候,由于前后端分离,根据同源策略两个服务不是同一个端口或者不是同域名,会造成跨域请求,如下图
Access to XMLHttpRequest at ‘http://localhost:8888/api/login/auth’ from origin ‘http://localhost:9520’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
意思是从http://localhost:9520 前端服务发起的请求到后端服务http://localhost:8888/api/login/auth 不能接受 No ‘Access-Control-Allow-Origin’ 不遵循同源策略
面对跨域一般有三种方式:1.前端jsonp、2.后端处理、3、服务器处理
这里就用到第三种服务器处理,我选择用nginx反向代理两个服务来实现他们在一个服务器上面 这样就遵循了同源策略
nginx根目录->conf->nginx.config
这个是http{ }里面的server
server {
listen 8888;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
#代理前端nodejs项目
location / {
proxy_set_header X_Real_IP $remote_addr;
proxy_set_header X-Forward-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_pass http://localhost:3000; #代理前端地址
proxy_redirect off;
}
#代理后台接口
location /api/ {
proxy_pass http://localhost:8080; #转发请求的地址
proxy_connect_timeout 6000; #链接超时设置
proxy_read_timeout 6000; #访问接口超时设置
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
使用服务器处理的好处:在不改动前后端代码的情况下,便捷的处理请求,由于是代理了两端的服务依旧能够热部署(热更新)
注意事项: 反向代理后,前端的请求地址要改为http://localhost:8888/api/ (因为都在nginx的8888端口上,这个地址就是代理的后端请求地址,浏览器可以访问,http://localhost:8888则是被反向代理的前端地址),然后后端接口也要增加/api
比如原来请求是@RequestMapping("/login"),代理后改为@RequestMapping("/api/login"),如果后端springboot用了shiro等安全框架 里面的拦截地址也要改
nginx配置文件
更多推荐
nginx反向代理前端服务到后端解决跨域
发布评论