1. 首先检查当前电脑是否安装了
brew -v
// 如果没有安装则执行以下命令,安装brew:
/bin/zsh -c "$(curl -fsSL https://gitee.com/cunkai/HomebrewCN/raw/master/Homebrew.sh)"
2. 检查是否安装了 nginx:
brew search nginx
// 如果没有安装 nginx,则使用以下命令来安装
brew install nginx
3. 查看nginx 本地配置文件(配置文件为该目录下的nginx.conf文件):
open /usr/local/etc/nginx/
4. 修改 nginx配置文件,解决跨域问题:
server {
# 当前代理的端口号(确保该端口号未被占用)
listen 5500;
server_name cc-client-old;
# 一般情况下的代理地址
location / {
proxy_pass http://localhost:5501;
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size 100m;
}
location /action {
# 特殊情况的代理地址;
proxy_pass https://www.baidu.com/action;
# 指定允许跨域的方法,*代表所有
add_header Access-Control-Allow-Methods *;
# 预检命令的缓存,如果不缓存每次会发送两次请求
add_header Access-Control-Max-Age 3600;
# 带cookie请求需要加上这个字段,并设置为true
add_header Access-Control-Allow-Credentials true;
# 表示允许这个域跨域调用(客户端发送请求的域名和端口)
# $http_origin动态获取请求客户端请求的域 不用*的原因是带cookie的请求不支持*号
add_header Access-Control-Allow-Origin $http_origin;
# 表示请求头的字段 动态获取
add_header Access-Control-Allow-Headers
$http_access_control_request_headers;
# OPTIONS预检命令,预检命令通过时才发送请求
# 检查请求的类型是不是预检命令
if ($request_method = OPTIONS){
return 200;
}
}
}
5. nginx 的启动:
// 以下命令当提醒没有权限时,命令行前加 sudo
// nginx的启动
nginx
// 查看当前 nginx 运行的进程
ps -ef | grep nginx
// 关闭某一个进程
kill [进程编号]
// 快速停止 nginx 进程
nginx -s stop
// 重启 nginx
nginx -s reload
// 搜索当前目录下有关键字 abc 的 nginx配置文件
grep abc * -r
6. nginx的使用:
前端代码在本地服务端口5501启动之后,如果所有的接口都访问的是 ./action,则需要将接口地址修改到别的地址,会比较麻烦而且可能出现跨域问题。此时可以使用本地代理,将 5500作为nginx 的代理地址,当浏览器访问5500端口时,默认转到 5501 端口访问前端页面,只有当访问 5500/action时转到代理地址 https://www.baidu.com/action 的接口。