跨域原理:http://www.cnblogs.com/Alear/p/8758331.html
介绍Ngnix之前,我么先来介绍下代理是什么~
代理相当于中间人,中介的概念
代理分为正向代理和反向代理。(PS:本文介绍的解决跨域方法用的是反向代理)
正向代理:现在客户端发送一个请求给服务端,可是该客户端没有访问权限,于是只能交给一个代理服务器来转交该客户端的请求给服务端响应。
客户端知道请求资源地址,也能感知代理服务器的存在。
反向代理:客户端发送一个请求,代理服务器收到这个请求,判断到这个请求对应的服务器并不能响应。于是代理服务器自行转发到可以响应该请求的服务器,并将响应内容返回给客户端。
客户端并不知道实际上是哪个服务器响应的内容 。
Ngnix是什么:
Nginx (engine x) 是一个高性能的HTTP和反向代理服务器。
安装Ngnix和基本配置介绍可以看下这篇~ :
Linux下: https://blog.csdn.net/yougoule/article/details/78186138
Window下:;https://www.cnblogs.com/saysmy/p/6609796.html
(PS)如果在window命令行操作出现下面这种情况
改成: .\nginx -s start (‘ngnix’ 换成 ‘ .\ngnix’)
接下来不废话了,我们来点实际的招式,直接上栗子,敲黑板!!!
我现在有一个项目是在 "localhost:80/test(等于localhost/test)下的"
可是我有个ajax请求是向localhost:8080/echarts/map请求的
如果直接请求浏览器的控制台会直接被报错
一般出现这种错误是跨域引起的
那么我们可以在ngnix配置文件nginx.conf(在ngnix安装目录下的conf文件下)这样配置来实现反向代理
nginx.conf
server {
listen 8081;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
root "D:/phpStudy/WWW";
location /echarts/map {
#rewrite localhost:8080/echarts/map break;
if ($request_method = 'OPTIONS') {
add_header Access-Control-Allow-Origin http://localhost;
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
return 200;
}
if ($request_method = 'POST') {
add_header 'Access-Control-Allow-Origin' http://localhost;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}
proxy_pass http://localhost:8080/echarts/map;
}
location /test/{
if ($request_method = 'OPTIONS') {
add_header Access-Control-Allow-Origin http://localhost;
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
return 200;
}
if ($request_method = 'POST') {
add_header 'Access-Control-Allow-Origin' *;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}
if ($request_method = 'GET') {
add_header 'Access-Control-Allow-Origin' *;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}
proxy_pass http://localhost:80;
#rewrite ^/localhost:80/941bigdata/
}