前端服务器部署分类总结

发布于:2025-05-15 ⋅ 阅读:(12) ⋅ 点赞:(0)

目前所了解的部署有三种方式:
一是本地服务器部署;二是 nginx 服务器部署;三是云服务器部署

本地部署,准备好部署的包

以Vue项目为例,执行npm run build 命令打成前端包
第二步:将打包结果交给服务器(本地使用 node.js创建的服务)

将打包生成的文件内容,放到服务器的静态资源文件夹中(含有 index.html的文件夹里)

第四步:测试访问前端项目

浏览器访问:http://localhost:8080即可看到我们的项目,但此时会遇到两个问题:

  1. 页面刷新 404
  2. ajax 请求无法发送

解决刷新 404 问题
问题分析:前端项目的路由,通常分为两种工作模式,分别为:

  • hash 模式(链接中带“#”,井号后面的值称为 hash 值,hash 值只在客户端(如浏览器)中使用,是不会带给服务器的,所以使用 hash 模式时,不存在刷新 404 问题。)
  • history 模式(history 去掉了URL中的#号,可以让应用的URL看起来更美观,带来的问题就是刷新时,会将前端路由携带给后端,而后端没有对应资源的匹配,就出现了 404 问题。)
    解决方案一:将前端路由器工作模式改为 hash 模式 —— 不太推荐(hash模式一般用于后台管理系统中,或者不对链接美观做要求的项目)。
    解决方案二:让服务器在收到未配置的GET路由时,都返回index.html即可。

方案二最终其实是把 url 中的 path,交给了前端路由去处理,具体配置如下:

app.get('*',(req,res)=>{
	res.sendFile(__dirname + '/public/index.html')
})

也可以借助connect-history-api-fallback中间件完成配置

const history = require('connect-history-api-fallback');
app.use(history());
// 配置静态资源
app.use(express.static(__dirname + '/public'))

使用connect-history-api-fallback可以让配置更灵活,比如/login临时不需要作为前端路由处理,就可以按照如下方式配置

app.use(history({
	verbose:false,
	rewrites:[
		{ from: /^\/login.*$/, to: (context) => context.parsedUrl.path },
	]
}))

请求无法发送问题:
问题分析:脱离脚手架后,就没有了代理服务器,无法转发请求到【提供数据】的服务器。
如何解决?—— 在 Node 服务器中借助http-proxy-middleware中间件配置代理,具体配置如下:

javascript
`// 引入createProxyMiddleware
const { createProxyMiddleware } = require('http-proxy-middleware')
// 配置代理中间件
app.use('/dev', createProxyMiddleware({
	target: 'http://xxx-h5-api.xxxxx.cn',
	changeOrigin: true,
	pathRewrite: {
		'^/dev': ''
	}
}))

nginx 服务器部署

nginx 简介:
Nginx(发音为“engine-x”)是一款高性能的 HTTP 服务器和反向代理服务器,同时也是一个 IMAP/POP3/SMTP 代理服务器。Nginx 最初由 Igor Sysoev 编写,于 2004 年发布。它以其高性能、高稳定性、丰富的功能集和低系统资源消耗而闻名,主要功能有:

  1. 反向代理
  2. 负载均衡
  3. 静态内容服务
  4. HTTP/2 支持
  5. SSL/TLS 支持
  6. 高速缓存

nginx 部署前端项目
整体思路:让nginx充当两个角色,既是 静态内容服务器,又是代理服务器。

  1. 修改nginx配置如下,注意nginx的根目录最好不是 C 盘
# 配置nginx根目录
location / {
  root   D:\dist;
  index  index.html index.htm;
}

# 配置代理
location /dev/ {
  # 设置代理目标
  proxy_pass http://xxx-h5-api.xxxxx.cn/;
}
  1. 修改前端项目,让所有请求都转发给 /dev,随后重新打包
const request = axios.create({
  baseURL:'/dev',
  timeout:10000
})
  1. 随后直接访问nginx服务器即可,例如 nginx如果运行在8099端口,则访问:
http://localhost:8099
  1. 随后会遇到刷新404问题,追加nginx配置来解决
# 配置nginx根目录
location / {
  root   D:\dist;
  index  index.html index.htm;
  try_files $uri $uri/ /index.html; # 解决刷新404
}
# 配置代理
location /dev/ {
  # 设置代理目标
  proxy_pass http://xxx-h5-api.xxxxx.cn/;
}

云服务器部署

我们可以在云服务器上借助nginx完成部署,大致流程与本地nginx部署一致

  1. 关于购买云服务器,可选择:阿里云、腾讯云等。
  2. 关于操作系统,看个人习惯,Ubuntu、CentOs、RedHat、都不错。
  3. 购买完成后记得重置密码
  4. linux 远程操作软件:XshellXftp
  5. 具体配置如下:

● 给服务器安装nginx

yum install nginx

● 将打包后的前端资源放在:/xxx/xxx文件夹中
● 使用Xftp配置服务器的 nginx,修改文件:/etc/nginx/nginx.config。

# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    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  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  _;
        root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location / {
          root   /var/sph;
          index  index.html index.htm;
          try_files $uri $uri/ /index.html; # 解决刷新404
        }
        # 配置代理
        location /dev/ { # dev前后的斜杠意义是,能兼容 后端API 接口带 dev或者不带 dev都可
          # 设置代理目标
          proxy_pass http://xxx-h5-api.xxxxx.cn/;
        }

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }
}

网站公告

今日签到

点亮在社区的每一天
去签到