文章列舉了node和nginx方式在Windows電腦部署前端服務(wù)袱箱。
1) node方式
啟動服務(wù)
- 新建
server-demo
文件夾垫桂,在當(dāng)前目錄打開終端依次執(zhí)行如下命令
npm init
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í)行
- 啟動
start nginx
- 強制停止
nginx -s stop
- 安全退出
nginx -s quit
- 重新加載配置文件(如果修改了配置文件就執(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的文件
- 自定義添加前端資源和接口請求配置
在nginx-1.24.0
文件夾中新建tikeyc
文件夾,將編譯好的前端文件放入tikeyc
文件夾,中 - 添加如下代碼
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;
# }
#}
}