node和nginx方式部署前端服務(wù)

文章列舉了node和nginx方式在Windows電腦部署前端服務(wù)袱箱。

1) node方式

啟動服務(wù)
  • 新建server-demo文件夾垫桂,在當(dāng)前目錄打開終端依次執(zhí)行如下命令
npm init

express中文網(wǎng)

yarn add express
  • server-demo文件夾下新建index.js文件,編寫如下代碼
const express = require('express')

const app = express()

const port = 1024

app.get('/tikeyc', (req, res) => {
  res.send({
    name: 'tikeyc',
    age: 18
  })
})

app.listen(port, (err) => {
  if (!err) {
    console.log('服務(wù)器啟動成功了on port:', port)
  }
})
  • package.json文件中的scripts中新增"start": "node index"
{
  "name": "server-demo",
  "version": "1.0.0",
  "description": "node server",
  "main": "index.js",
  "scripts": {
    "start": "node index",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "node",
    "server"
  ],
  "author": "tikeyc",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.2"
  }
}

  • 啟動服務(wù)執(zhí)行命令
yarn start

打印: 服務(wù)器啟動成功了on port:1024

  • 瀏覽器訪問http://localhost:1024/tikeyc顯示如下
    {"name":"tikeyc","age":18}
訪問編譯后的前端資源

為了提供諸如圖像栗涂、CSS 文件和 JavaScript 文件之類的靜態(tài)文件署驻,請使用 Express 中的 express.static 內(nèi)置中間件函數(shù)。
此函數(shù)特征如下:

express.static(root, [options])
  • server-demo文件夾下新建static文件夾將編譯好的前端資源拷貝至static文件夾中
  • index.js文件中新增如下代碼
app.use(express.static(__dirname + '/static'))

Express 在靜態(tài)目錄查找文件,因此买置,存放靜態(tài)文件的目錄名不會出現(xiàn)在 URL 中粪糙。
如果要使用多個靜態(tài)資源目錄,請多次調(diào)用 express.static 中間件函數(shù):

app.use(express.static(__dirname + 'static'))
app.use(express.static(__dirname + 'files'))

完整代碼是:

const express = require('express')

const app = express()

const port = 1024

app.get('/tikeyc', (req, res) => {
  res.send({
    name: 'tom',
    age: 18
  })
})

// app.use(express.static(__dirname + '/static'))
// 可以通過帶有 /node-server 前綴地址來訪問 static 目錄中的文件
app.use('/node-server', express.static(__dirname + '/static'))

app.use(express.static(__dirname + '/files'))

app.listen(port, (err) => {
  if (!err) {
    console.log('服務(wù)器啟動成功了on port:', port)
  }
})
  • 重啟服務(wù)
yarn start
  • 訪問前端界面localhost:1024/node-server

  • 跨域配置
    終端執(zhí)行

yarn add http-proxy-middleware
  • server-demo文件夾下新建index.js文件忿项,新增如下代碼
const { createProxyMiddleware } = require('http-proxy-middleware');

app.use('/api', createProxyMiddleware({
  target: 'http://xxxx.xxx.xx',
  pathRewrite: {
    '/test/api': '/api'
  },
  changeOrigin: true,
  secure: true,
}));

最終

const express = require('express')
const { createProxyMiddleware } = require('http-proxy-middleware');

const app = express()

const port = 1024

app.get('/tikeyc', (req, res) => {
  res.send({
    name: 'tom',
    age: 18
  })
})

// app.use(express.static(__dirname + '/static'))
// 可以通過帶有 /node-server 前綴地址來訪問 static 目錄中的文件
app.use('/node-server', express.static(__dirname + '/static'))

app.use(express.static(__dirname + '/files'))

app.use('/api', createProxyMiddleware({
  target: 'http://xxxx.xxx.xx',
  pathRewrite: {
    '/test/api': '/api'
  },
  changeOrigin: true,
  secure: true,
}));

app.listen(port, (err) => {
  if (!err) {
    console.log('服務(wù)器啟動成功了on port:', port)
  }
})

注意蓉冈,每次編輯index.js文件需要重啟服務(wù)

  • 上傳文件
yarn add multer body-parser
const multer = require('multer');
const bodyParser = require('body-parser');

// 使用body-parser中間件來解析請求體中的JSON數(shù)據(jù)
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 配置multer的存儲選項
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './uploads') // 設(shè)置文件存儲的目錄
  },
  filename: function (req, file, cb) {
    const fileFormat = (file.originalname).split("."); // 獲取文件后綴
    // const newName = file.fieldname + '-' + Date.now() + "." + fileFormat[fileFormat.length - 1]; // 重命名文件
    const newName = file.originalname + "." + fileFormat[fileFormat.length - 1]; // 重命名文件
    cb(null, newName); // 使用新的文件名
  }
});

// 創(chuàng)建multer實例
const upload = multer({ storage: storage });

// 處理文件上傳的路由
app.post('/upload', upload.single('file'), (req, res) => {
  if (!req.file) {
    return res.status(400).send('No file uploaded.');
  }

  // req.file 是 'file' 字段中的文件信息
  // 它包含了文件名、文件類型轩触、文件大小等信息
  // 以及文件在臨時目錄中的路徑

  // 你可以將文件從臨時目錄移動到你的目標目錄
  // 例如寞酿,移動到Windows電腦的某個本地目錄
  const targetPath = `E:/node-server/uploadFile/${req.file.originalname}`;
  console.log(11111, req.file);
  // req.file.mv(targetPath, (err) => {
  //   if (err) {
  //     return res.status(500).send('Error uploading file.');
  //   }
  //   res.send('File uploaded successfully.');
  // });
  res.send('File uploaded successfully.');
});

2) nginx方式

  • 安裝nginx 我下載的window穩(wěn)定版版本,解壓到不含中文的文件夾中,比如D:\Nginx\nginx-1.24.0
Mainline version:Mainline 是 Nginx 目前主力在做的版本脱柱,可以說是開發(fā)版
Stable version:最新穩(wěn)定版伐弹,生產(chǎn)環(huán)境上建議使用的版本
Legacy versions:遺留的老版本的穩(wěn)定版
  • 啟動nginx,直接vscode打開nginx-1.24.0文件夾
    nginx-1.24.0目錄下打開終端執(zhí)行
  1. 啟動
start nginx
  1. 強制停止
nginx -s stop
  1. 安全退出
nginx -s quit
  1. 重新加載配置文件(如果修改了配置文件就執(zhí)行這行命令榨为,否則修改就是無效的惨好。前提:nginx服務(wù)是啟動的狀態(tài)煌茴,否則reload是不成功的。)
nginx -s reload 
  • 部署前端文件
    將編譯好的前端文件放入nginx-1.24.0/html文件夾中
    瀏覽器訪問http://localhost
  • 配置nginx服務(wù)
    vscode打開nginx-1.24.0/conf/nginx.conf文件
location 語法一共有四種:
location = /aaa 是精確匹配 /aaa 的路由;
location /bbb 是前綴匹配 /bbb 的路由日川。
location ~ /ccc.*.html 是正則匹配蔓腐,可以再加個 * 表示不區(qū)分大小寫 location ~* /ccc.*.html;
location ^~ /ddd 是前綴匹配,但是優(yōu)先級更高龄句。

這 4 種語法的優(yōu)先級是:
精確匹配(=) > 高優(yōu)先級前綴匹配(^~) > 正則匹配(~ / ~*) > 普通前綴匹配

root 與 alias(需要注意的是alias后面必須要用/結(jié)束回论,否則會找不到文件的,而root則可有可無):
1分歇、root的處理結(jié)果是:root路徑 + location路徑;
location ^~ /test/ {
    root /xxx/root/html/;
} 
請求的url是 /test/index.html時傀蓉,將會返回服務(wù)器上的/xxx/root/html/test/index.html的文件

2、alias的處理結(jié)果是:使用alias路徑替換location路徑;
location ^~ /test/ {
    alias /xxx/root/html/new-test/;
}
請求的url是 /test/index.html 時卿樱,將會返回服務(wù)器上的/xxx/root/html/new-test/index.html的文件
  1. 自定義添加前端資源和接口請求配置
    nginx-1.24.0文件夾中新建tikeyc文件夾,將編譯好的前端文件放入tikeyc文件夾,中
  2. 添加如下代碼
location /tikeyc {
    alias  tikeyc/;
    index  index.html index.htm;
}
# 前端接口請求代理配置
location /tikeyc/api/ {
    # 這行代碼就說明請求會代理到 http://xxxx.xxx.xx
    proxy_pass http://xxxx.xxx.xx;
}

執(zhí)行

.\nginx -s reload

瀏覽器訪問http://localhost/tikeyc查看前端界面
最終

#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 / {
            root   html;
            index  index.html index.htm;
            # 這行代碼就說明請求會代理到 http://localhost:1024/test
            # proxy_pass http://localhost:1024/test;
            # 這行代碼就說明請求會代理到 https://www.baidu.com
            proxy_pass https://www.baidu.com;
        }
        # 訪問前端資源代理配置
        location /test {
            alias  tikeyc/;
            index  index.html index.htm;
        }
        # 前端接口請求代理配置
        location /test/api {
            # 這行代碼就說明請求會代理到 http://xxxx.xxx.xx
            proxy_pass http://xxxx.xxx.xx;
        }

        #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;
    #    }
    #}

}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末僚害,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子繁调,更是在濱河造成了極大的恐慌萨蚕,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,542評論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件蹄胰,死亡現(xiàn)場離奇詭異岳遥,居然都是意外死亡,警方通過查閱死者的電腦和手機裕寨,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,822評論 3 394
  • 文/潘曉璐 我一進店門浩蓉,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人宾袜,你說我怎么就攤上這事捻艳。” “怎么了庆猫?”我有些...
    開封第一講書人閱讀 163,912評論 0 354
  • 文/不壞的土叔 我叫張陵认轨,是天一觀的道長。 經(jīng)常有香客問我月培,道長嘁字,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,449評論 1 293
  • 正文 為了忘掉前任杉畜,我火速辦了婚禮纪蜒,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘此叠。我一直安慰自己纯续,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,500評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著杆烁,像睡著了一般牙丽。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上兔魂,一...
    開封第一講書人閱讀 51,370評論 1 302
  • 那天烤芦,我揣著相機與錄音,去河邊找鬼析校。 笑死构罗,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的智玻。 我是一名探鬼主播遂唧,決...
    沈念sama閱讀 40,193評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼吊奢!你這毒婦竟也來了盖彭?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,074評論 0 276
  • 序言:老撾萬榮一對情侶失蹤页滚,失蹤者是張志新(化名)和其女友劉穎召边,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體裹驰,經(jīng)...
    沈念sama閱讀 45,505評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡隧熙,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,722評論 3 335
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了幻林。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片贞盯。...
    茶點故事閱讀 39,841評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖沪饺,靈堂內(nèi)的尸體忽然破棺而出躏敢,到底是詐尸還是另有隱情,我是刑警寧澤整葡,帶...
    沈念sama閱讀 35,569評論 5 345
  • 正文 年R本政府宣布件余,位于F島的核電站,受9級特大地震影響掘宪,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜攘烛,卻給世界環(huán)境...
    茶點故事閱讀 41,168評論 3 328
  • 文/蒙蒙 一魏滚、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧坟漱,春花似錦鼠次、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,783評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽成翩。三九已至,卻和暖如春赦役,著一層夾襖步出監(jiān)牢的瞬間麻敌,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,918評論 1 269
  • 我被黑心中介騙來泰國打工掂摔, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留术羔,地道東北人。 一個月前我還...
    沈念sama閱讀 47,962評論 2 370
  • 正文 我出身青樓乙漓,卻偏偏與公主長得像级历,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子叭披,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,781評論 2 354

推薦閱讀更多精彩內(nèi)容