经常需要研发在本地环境进行接口和部分简单的前端代码联调,我们会发经常出现跨域请求问题。如果解决跨域请求问题,可能就要修改相关后台代码,但是生产环境由于域名的处理又不会出现域名问题,所以没有必要进行兼容跨域问题的处理。我这边给出解决方案为基于nginx。
1、期望达到的目标
本地的文件在请求本机的接口(比如localhost:8081/test/helloworld)时可以正常返回。 电脑:mac ,前端代码html,使用jquery请求接口
2、先在本机安装nginx
本地起webserver有很多的中方式。比如使用python比较简单。
cd path/to/your/html/file
python -m http.server 8000
比如node.js
npm install -g http-server
cd path/to/your/html/file
http-server
此处我们使用nginx作为webserver,因为我们后面要进行跨域问题的解决 如果没有安装brew先安装brew。如果地址不通,网络上有很多的方式,这边不在赘叙
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
安装nginx
brew update
brew install nginx
brew services start nginx
注意一下端口的占用情况,如果端口被占用了可以使用下面的方法查看端口被占用的pid和停止进程。
lsof -i :8080
sudo kill -9 pid
3、配置nginx
一般nginx是安装在/opt/homebrew/etc/nginx/
下,我们打开nginx.conf 进行相关配置就完成打开html和代理后台站点
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
server {
listen 8080;
server_name ***.test.com; # 服务器地址或绑定域名
location / {
root /path/to/html/location;
index index.html;
}
location /api/ {
proxy_pass http://localhost:8081;
proxy_set_header Host $host;
proxy_set_header x-real-ip $remote_addr;
proxy_set_header x_forward-for $proxy_add_x_forwarded_for;
}
}
include servers/*;
}
然后我们进行nginx重载
nginx -s reload
4、配置本机host
进行hosts文件
sudo vi /etc/hosts
添加域名映射:127.0.0.1 ***.test.com
此时我们再次打开html,接口地址改成***.test.com/api/ 访问已经可以正常访问了。
如果还是有跨域,就应该js的代码写得有问题,参照下面:
$.ajax({
type: "post",
url: "http://***.test.com:8080/api/passport/login",
contentType: "application/json;charset=utf-8",
data: JSON.stringify({
userName: 111,
password: 2222
}),
success: function (res) {
}
});