node和nginx方式部署前端服务

文章列举了node和nginx方式在Windows电脑部署前端服务。

1) node方式

启动服务
  • 新建server-demo文件夹,在当前目录打开终端依次执行如下命令
npm init

express中文网

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目录下打开终端执行
  1. 启动
start nginx
  1. 强制停止
nginx -s stop
  1. 安全退出
nginx -s quit
  1. 重新加载配置文件(如果修改了配置文件就执行这行命令,否则修改就是无效的。前提: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的文件
  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;
}

执行

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

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,002评论 6 509
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,777评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,341评论 0 357
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,085评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,110评论 6 395
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,868评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,528评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,422评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,938评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,067评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,199评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,877评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,540评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,079评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,192评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,514评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,190评论 2 357

推荐阅读更多精彩内容