Nginx下載
-
概念
1. 高性能web服務(wù)器
2. 一般用作靜態(tài)服務(wù)器, 負(fù)載均衡
3. 反向代理(跨域)
nginx.png -
下載
- win下載: 官網(wǎng)下載
http://nginx.org/en/download.html - mac下載:
brew install nginx
- win下載: 官網(wǎng)下載
-
配置文件
- win:
C:\nginx\conf\nginx.conf - mac:
/usr/local/etc/nginx/nginx.conf
- win:
-
Nginx命令
- 檢測配置文件格式是否正確:
nginx -t - 啟動nginx, 重啟nginx:
nginx -s reload - 停止:
nginx -s stop - Mac 打開配置文件:
sudo vi /usr/local/etc/nginx/nginx.conf(也可直接編輯)
- 檢測配置文件格式是否正確:
Nginx實現(xiàn)跨域
第一步 node服務(wù)端
const http = require('http')
const url = require('url')
const server = http.createServer((req, res) => {
const { method } = req
const { pathname } = url.parse(req.url)
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' })
if (pathname === '/list' && method === 'GET') {
const data = JSON.stringify({ username: 'test', pwd: 123 })
console.log(pathname);
res.end(data)
} else {
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' })
res.end('404 not found')
}
})
server.listen(3000, () => {
console.log('listen port at 3000')
})
第二步 web客戶端
<!--通過http-server -p 3001 將客戶端啟動-->
<body>
測試頁面
<script src="https://cdn.bootcss.com/axios/0.19.2/axios.js"></script>
<script>
axios.get('http://localhost:3002/list').then(data => {
console.log(data)
})
</script>
</body>
第三步 配置nginx
# 設(shè)定http服務(wù)器, 之后請求都是http不是https
http {
server {
listen 3002; # 偵聽3002端口
server_name localhost; # 客戶端域名
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS';
# 靜態(tài)資源的地址, 可不配置也能實現(xiàn)跨域
# location / {
# root C:/Users/80021648/Desktop/js; #定義服務(wù)器的默認(rèn)網(wǎng)站根目錄位置
# index index.html index.htm app.html; #定義首頁索引文件的名稱
# }
location /list{
proxy_pass http://localhost:3000/list; # 代理轉(zhuǎn)發(fā)的服務(wù)端地址
}
}
}
總結(jié)
服務(wù)端: http://localhost:3000
客戶端: http://localhost:3001
nginx: http://localhost:3002
客戶端請求nginx監(jiān)聽的端口, nginx監(jiān)聽到端口請求, 然后代理轉(zhuǎn)發(fā)的服務(wù)端地址
客戶端 -> 服務(wù)端
axios.get('http://localhost:3000/list')
變成 客戶端 -> nginx代理轉(zhuǎn)發(fā) -> 服務(wù)端
axios.get('http://localhost:3002/list')
