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

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

1) node方式

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

express中文網(wǎng)

yarn add express
  • server-demo文件夾下新建index.js文件,編寫(xiě)如下代碼
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ù)器啟動(dòng)成功了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"
  }
}

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

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

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

為了提供諸如圖像、CSS 文件和 JavaScript 文件之類(lèi)的靜態(tài)文件,請(qǐng)使用 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)文件的目錄名不會(huì)出現(xiàn)在 URL 中。
如果要使用多個(gè)靜態(tài)資源目錄,請(qǐng)多次調(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'))
// 可以通過(guò)帶有 /node-server 前綴地址來(lái)訪問(wèn) static 目錄中的文件
app.use('/node-server', express.static(__dirname + '/static'))

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

app.listen(port, (err) => {
  if (!err) {
    console.log('服務(wù)器啟動(dòng)成功了on port:', port)
  }
})
  • 重啟服務(wù)
yarn start
  • 訪問(wèn)前端界面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'))
// 可以通過(guò)帶有 /node-server 前綴地址來(lái)訪問(wèn) 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ù)器啟動(dòng)成功了on port:', port)
  }
})

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

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

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

// 配置multer的存儲(chǔ)選項(xiàng)
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './uploads') // 設(shè)置文件存儲(chǔ)的目錄
  },
  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實(shí)例
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' 字段中的文件信息
  // 它包含了文件名、文件類(lèi)型、文件大小等信息
  // 以及文件在臨時(shí)目錄中的路徑

  // 你可以將文件從臨時(shí)目錄移動(dòng)到你的目標(biāo)目錄
  // 例如,移動(dòng)到Windows電腦的某個(gè)本地目錄
  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 目前主力在做的版本,可以說(shuō)是開(kāi)發(fā)版
Stable version:最新穩(wěn)定版,生產(chǎn)環(huán)境上建議使用的版本
Legacy versions:遺留的老版本的穩(wěn)定版
  • 啟動(dòng)nginx,直接vscode打開(kāi)nginx-1.24.0文件夾
    nginx-1.24.0目錄下打開(kāi)終端執(zhí)行
  1. 啟動(dòng)
start nginx
  1. 強(qiáng)制停止
nginx -s stop
  1. 安全退出
nginx -s quit
  1. 重新加載配置文件(如果修改了配置文件就執(zhí)行這行命令,否則修改就是無(wú)效的。前提:nginx服務(wù)是啟動(dòng)的狀態(tài),否則reload是不成功的。)
nginx -s reload 
  • 部署前端文件
    將編譯好的前端文件放入nginx-1.24.0/html文件夾中
    瀏覽器訪問(wèn)http://localhost
  • 配置nginx服務(wù)
    vscode打開(kāi)nginx-1.24.0/conf/nginx.conf文件
location 語(yǔ)法一共有四種:
location = /aaa 是精確匹配 /aaa 的路由;
location /bbb 是前綴匹配 /bbb 的路由。
location ~ /ccc.*.html 是正則匹配,可以再加個(gè) * 表示不區(qū)分大小寫(xiě) location ~* /ccc.*.html;
location ^~ /ddd 是前綴匹配,但是優(yōu)先級(jí)更高。

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

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

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

執(zhí)行

.\nginx -s reload

瀏覽器訪問(wèn)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;
            # 這行代碼就說(shuō)明請(qǐng)求會(huì)代理到 http://localhost:1024/test
            # proxy_pass http://localhost:1024/test;
            # 這行代碼就說(shuō)明請(qǐng)求會(huì)代理到 https://www.baidu.com
            proxy_pass https://www.baidu.com;
        }
        # 訪問(wèn)前端資源代理配置
        location /test {
            alias  tikeyc/;
            index  index.html index.htm;
        }
        # 前端接口請(qǐng)求代理配置
        location /test/api {
            # 這行代碼就說(shuō)明請(qǐng)求會(huì)代理到 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)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容