由于后端接口与前端布置的服务器地址和端口的不一致,都会导致跨域不允许。类似于下图这种,

动后端代码和前端代码(type:jsonp等)都可以,但是我们不这么做,
这时候我们可以采用nginx来解决跨域问题,
原理大致是:通过nginx配置一个代理服务器做跳板机,反向代理后端接口
第一步:
先配置nginx.config,直接贴代码
server {
listen 8000;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root E:/h5; #h5项目路径
}
location /urm { #代理的接口路径
proxy_pass http://192.168.1.111:9003/urm;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
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-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}
location = /favicon.ico {
log_not_found off;
access_log off;
}
}
第二步:
启动后端服务器,启动nginx
第三步:
修改前端ajax访问的url,
http://192.168.1.111:9003/urm
→
http://192.168.1.111:8000/urm
第四步:
访问前端项目,
http://192.168.1.111:8000/agent/merchant_manage.html
结束。。