前端跨域是经常遇到的问题,如何解决跨域问题,常用的办法就是采用nginx代理。和ajax联合使用可以有效解决跨域的问题。
不说废话,直接码代码:常见的几种nginx代理方法:
1.代理网页:
多数后台服务器网页不能直接访问,需要进行代理之后才能解决跨域问题。nginx中代理的端口设置是85,后续默认都是85
location /topo {
proxy_pass http://localhost:5000/Topo;
}
需要代理的网页是 http://localhost:5000/Topo,代理后的网页是 http://localhost:85/topo,前台获取http://localhost:5000/Topo的内容可以通过获取http://localhost:85/topo,解决跨域问题。
2.代理本地文件
由于前段开发会设计到本地资源的加载,因此需要代理本地的资源,包括(image/js/css)等多种文件。
location ~ ^/(image/js/css)/ {
add_header 'Access-Control-Allow-Methods' 'GET,OPTIONS,PUT,DELETE' always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Allow-Origin' '$http_origin' always;
add_header 'Access-Control-Allow-Headers' 'Authorization,DNT,User-Agent,Keep-Alive,Content-Type,accept,origin,X-Requested-With' always;
root D:\demo;
access_log off;
expires 30d;
}
其中(image/js/css)都是处于demo文件下的子文件,例如现在访问D:\demo\image\1.jpg;对应线上的访问地址就是http://localhost:85/image/1.jpg,从而实现本地资源加载到线上。
3.nginx批量配置带参数的网址
后台产生的网址的会出现带有参数的网址,例如http:localhost:5000/test/1, http:localhost:5000/test/2, http:localhost:5000/test/3, http:localhost:5000/test/4,对于最后的参数如果只有个位数的级别,采用nginx能够实现一个一个配置,但是如果是后面是几百个或者更多,一个一个配置不合理,不仅会导致代码量的增加,而且增加理解的难度。如何实现批量配置,可以有效解决一个一个配置的问题。解决方法其代码如下,其中本地配置的端口是85。
location /test/ {
proxy_pass http://localhost:5000/test/;
}
通过采用预留参数的配置,可以实现在网页后面加入任意参数,配置后的网址添加相同的参数,即可以配置相同参数的网页,例如原始网页是http:localhost:5000/test/1,配置后对应的网页就是http:localhost:85/test/1,从而实现批量配置,减少代码的冗余,增加代码的可读性。