登錄依賴cookie,且cookie是跨域不共享的,如果是前后臺分離開發(fā),肯定存在跨域的情況,有時需要在服務(wù)器上同時啟動前后臺服務(wù),然后使用nginx服務(wù)器配置反向代理來解決前后臺跨域問題
參考:https://www.runoob.com/linux/nginx-install-setup.html
步驟
- 下載:https://nginx.org/en/download.html (下載速度很快,壓縮包)
- 解壓到指定位置,比如C盤根目錄,并重命名為nginx
- 使用vscode打開 windows:C:\nginx\conf\nginx.conf
- 參數(shù):
worker_processes 1; (cpu是幾核的,負(fù)載均衡)
listen 9090; (監(jiān)聽端口)
proxy_pass http://localhost:9001; (前臺服務(wù)端口)
proxy_pass http://localhost:9000; (后臺服務(wù)端口) - 可以做多服務(wù)跨域處理
#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 9090;
server_name localhost;
location / {
proxy_pass http://localhost:9001;
}
location /dev-api/ {
proxy_pass http://localhost:9000;
proxy_set_header Host $host;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
server {
listen 3030;
server_name localhost;
location / {
proxy_pass http://localhost:3001;
}
location /api/ {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;
# location / {
# root html;
# index index.html index.htm;
# }
#}
# HTTPS server
#
#server {
# listen 443 ssl;
# server_name localhost;
# ssl_certificate cert.pem;
# ssl_certificate_key cert.key;
# ssl_session_cache shared:SSL:1m;
# ssl_session_timeout 5m;
# ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_prefer_server_ciphers on;
# location / {
# root html;
# index index.html index.htm;
# }
#}
}
- 保存測試
用vscode或者win+R cmd 打開windows:C:\nginx
輸入:start nginx
然后:nginx -t 檢測是否成功啟動,出現(xiàn)以下字樣,代表nginx啟動成功
nginx: the configuration file C:\nginx/conf/nginx.conf syntax is ok
nginx: configuration file C:\nginx/conf/nginx.conf test is successful - 跨域測試
瀏覽器輸入:http://localhost:9090/index.html (此端口是監(jiān)聽端口,非前后端服務(wù)端口)
打開頁面后,前端服務(wù)可以正常訪問接口,證明nginx跨域代理成功 - nginx 常用命令
啟動:start nginx 或者 nginx
重啟:nginx -s reload
停止:nginx -s stop
檢測是否成功:nginx -t