本文原創,轉載請附上原作者連結!https://www.cnblogs.com/LSWu/articles/14848324.html

1.安裝node.js

從node.js官網上下載node.js的LTS安裝包,然後正常安裝即可,安裝完成後,node.js自帶的npm工具也會相應的安裝好。然後在命令列下輸入node -v和npm -v,返回如下資訊說明安裝成功。

1 lishanwu@Lenovo-PC MINGW64 ~/Desktop/nodejs_test
2 $ node -v
3 v14.16.1
4
5 lishanwu@Lenovo-PC MINGW64 ~/Desktop/nodejs_test
6 $ npm -v
7 6.14.12

2.安裝nginx伺服器

  從nginx官網上下載對應windows的LTS的nginx壓縮包,然後解壓到目標目錄即可,然後雙擊ngnix.exe,或者在當前目錄下開啟命令列,輸入nginx.exe ,即可啟動nginx伺服器。然後在瀏覽器上輸入localhost,看到如下畫面則認為nginx已經安裝完成。如果想關閉nginx,則在命令列下輸入nginx -s stop即可關閉nginx伺服器,重啟伺服器則使用nginx -s reload

注意如果在git下,則使用./nginx.exe來啟動伺服器,使用./nginx.exe -s stop來停止伺服器,使用./nginx.exe -s reload來重啟伺服器。

3.配置nginx進行反代理

  nginx的解壓後有一個conf目錄,下面存放著很多匹配檔案,想要讓nginx進行反代理服務,需要對nginx.conf檔案進行配置。修改nginx.conf檔案如下所示

#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 80;
server_name localhost; #charset koi8-r; #access_log logs/host.access.log main; #這裡簡單設定一下反向代理
location /api/ {
proxy_pass http://192.168.x.xxx:4000; #我的本機ipv4地址,最好不要用localhost或者127.0.0.1,血的教訓<-_->
}
     #我的nodejs所在主機的ip為192.168.xxx.x:4000    
     #我的nginx所在主機的ip為192.168.xxx.x,將這裡改為自己的本機ip,我不想被網路攻擊,所以不能貼出我的ip
location / {
root html;
index index.html index.htm;
} #error_page 404 /404.html; # redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
} # proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#} # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#} # deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
} # 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;
# }
#} }

  然後重啟nginx伺服器,注意在程序管理器中確保在重啟前關閉nginx的程序,然後再啟動nginx伺服器。

4.編寫nodejs後端的測試程式碼,然後啟動nodejs服務

  main.js如下所示

var express = require('express');
var app = express();
var fs = require("fs"); app.get('/api/test0', function (req, res) {
console.log(req.url);
res.setHeader("Content-Type", "text/html;charset=utf-8")
res.end( "<h2>accessed test0</h2>" );
}) app.get('/api/test1', function (req, res) {
res.setHeader("Content-Type", "text/html;charset=utf-8")
res.end( "<h2>accessed test1</h2>" );
}) app.get('/api/test1/setting', function (req, res) {
res.setHeader("Content-Type", "text/html;charset=utf-8")
res.end( "<h2>this is setting of test1</h2>" );
}) var server = app.listen(4000, function () {
var host = server.address().address
var port = server.address().port
console.log("應用例項,訪問地址為 http://%s:%s", host, port)
})

  啟動nodejs前需要下載express依賴包,使用npm install  --save express,然後node main.js啟動nodejs服務(注意不要關了,否則nginx無法訪問)。

5.測試

  在瀏覽器中輸入http://localhost/api/test0 ,可以看到如下所示的結果,說明通過nginx反代理成功訪問到nodejs,注意這裡沒有加埠號,預設通過80埠訪問nginx。

  然後在瀏覽器中輸入http://localhost/api/test1 ,可以看到如下所示結果

  接著再輸入http://localhost/api/test1/setting,可以看到如下結果

  從上面可以看到,通過訪問不同的url可以將其通過nginx反向代理到nodejs中,nodejs並將處理的結果返回給nginx,然後nginx再將結果返回個瀏覽器。方向代理有一個很大的好處就是可以實現負載均衡和跨域訪問。

6.總結

  在使用nginx進行反代理的時候很容易將其反代理的ip或域名設為127.0.0.1或localhost,經過多次試驗發現,當設定為localhost後,需要重新整理頁面兩次才有返回結果,這顯然不正常,而使用127.0.0.1後,有多次直接返回404,所以為了確保每次都能正常訪問,最好將nginx的反代理的ip設為本機ip,例如192.168.xxx.x,域名則設定為備案後的域名(大陸),對於本機,在windows下使用ipconfig命令檢視ip地址,linux下使用ifconfig檢視ip地址。網上的教程大多都是直接設定localhost或者127.0.0.1,筆者強烈建議將其設定為本機ip