文章列举了node和nginx方式在Windows电脑部署前端服务。
1) node方式
启动服务
- 新建
server-demo
文件夹,在当前目录打开终端依次执行如下命令
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('服务器启动成功了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"
}
}
- 启动服务执行命令
yarn start
打印: 服务器启动成功了on port:1024
- 浏览器访问
http://localhost:1024/tikeyc
显示如下
{"name":"tikeyc","age":18}
访问编译后的前端资源
为了提供诸如图像、CSS 文件和 JavaScript 文件之类的静态文件,请使用 Express 中的 express.static 内置中间件函数。
此函数特征如下:
express.static(root, [options])
-
server-demo
文件夹下新建static
文件夹将编译好的前端资源拷贝至static
文件夹中 - 在
index.js
文件中新增如下代码
app.use(express.static(__dirname + '/static'))
Express 在静态目录查找文件,因此,存放静态文件的目录名不会出现在 URL 中。
如果要使用多个静态资源目录,请多次调用 express.static 中间件函数:
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('服务器启动成功了on port:', port)
}
})
- 重启服务
yarn start
访问前端界面
localhost:1024/node-server
跨域配置
终端执行
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('服务器启动成功了on port:', port)
}
})
注意,每次编辑index.js
文件需要重启服务
- 上传文件
yarn add multer body-parser
const multer = require('multer');
const bodyParser = require('body-parser');
// 使用body-parser中间件来解析请求体中的JSON数据
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// 配置multer的存储选项
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads') // 设置文件存储的目录
},
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); // 使用新的文件名
}
});
// 创建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稳定版版本,解压到不含中文的文件夹中,比如
D:\Nginx\nginx-1.24.0
Mainline version:Mainline 是 Nginx 目前主力在做的版本,可以说是开发版
Stable version:最新稳定版,生产环境上建议使用的版本
Legacy versions:遗留的老版本的稳定版
- 启动nginx,直接vscode打开
nginx-1.24.0
文件夹
在nginx-1.24.0
目录下打开终端执行
- 启动
start nginx
- 强制停止
nginx -s stop
- 安全退出
nginx -s quit
- 重新加载配置文件(如果修改了配置文件就执行这行命令,否则修改就是无效的。前提:nginx服务是启动的状态,否则reload是不成功的。)
nginx -s reload
- 部署前端文件
将编译好的前端文件放入nginx-1.24.0/html
文件夹中
浏览器访问http://localhost
- 配置nginx服务
vscode打开nginx-1.24.0/conf/nginx.conf
文件
location 语法一共有四种:
location = /aaa 是精确匹配 /aaa 的路由;
location /bbb 是前缀匹配 /bbb 的路由。
location ~ /ccc.*.html 是正则匹配,可以再加个 * 表示不区分大小写 location ~* /ccc.*.html;
location ^~ /ddd 是前缀匹配,但是优先级更高。
这 4 种语法的优先级是:
精确匹配(=) > 高优先级前缀匹配(^~) > 正则匹配(~ / ~*) > 普通前缀匹配
root 与 alias(需要注意的是alias后面必须要用/结束,否则会找不到文件的,而root则可有可无):
1、root的处理结果是:root路径 + location路径;
location ^~ /test/ {
root /xxx/root/html/;
}
请求的url是 /test/index.html时,将会返回服务器上的/xxx/root/html/test/index.html的文件
2、alias的处理结果是:使用alias路径替换location路径;
location ^~ /test/ {
alias /xxx/root/html/new-test/;
}
请求的url是 /test/index.html 时,将会返回服务器上的/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;
}
执行
.\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;
# }
#}
}