08、安装Nginx部署前端项目
2026-10-09 · 项目部署流程
1、安装Nginx
安装:https://nginx.org/en/linux_packages.html
本次采用yum安装
sudo yum install nginx -y
2、Nginx常用目录
- 配置文件
nginx.conf:/etc/nginx - 静态文件目录:
/usr/share/nginx
3、Nginx启动命令
# 启动
sudo systemctl start nginx
# 查看状态
systemctl status nginx
# 重载配置文件
sudo nginx -t # 先测试配置文件是否有误(强烈推荐)
sudo systemctl reload nginx
4、初始化一个VUE项目
# 使用 Vue CLI 初始化
# 安装 Vue CLI(如果还没装)
npm install -g @vue/cli
# 创建项目
vue create my-vue-app
# 进入项目目录并启动
cd my-vue-app
yarn serve
初始化出来的 App.vue 长这样:
<template>
<img alt="Vue logo" src="./assets/logo.png">
<HelloWorld msg="Welcome to Your Vue.js App"/>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
export default {
name: 'App',
components: {
HelloWorld
}
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
5、项目打包
yarn build
将dist目录上传到nginx静态目录/usr/share/nginx
6、修改请求后端接口
给 App.vue 加一个按钮,点击后请求后端接口:
<template>
<img alt="Vue logo" src="./assets/logo.png">
<HelloWorld msg="Welcome to Your Vue.js App"/>
<button @click="fetchData">请求接口</button>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
export default {
name: 'App',
components: {
HelloWorld
},
methods: {
async fetchData() {
try {
const response = await fetch('http://127.0.0.1:8001/test');
const data = await response.text();
alert(data);
} catch (error) {
alert('请求失败: ' + error.message);
}
}
}
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
7、后端跨域
两种方式都可以,推荐配置文件
/**
* @Author: xueqimiao
* @Date: 2025/7/28 16:30
*/
@RestController
@CrossOrigin
public class TestController {
// http://127.0.0.1:8001/test
@RequestMapping("/test")
public String test() {
return "hello";
}
}
- 配置文件
package com.xx.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*") //允许跨域的域名,可以用*表示允许任何域名使用
.allowedMethods("*") //允许任何方法(post、get等)
.allowedHeaders("*") //允许任何请求头
.allowCredentials(true) //带上cookie信息
.exposedHeaders(HttpHeaders.SET_COOKIE)
.maxAge(3600L); //maxAge(3600)表明在3600秒内,不需要再发送预检验请求,可以缓存该结果
}
};
}
}
8、前后端全部重新部署一下
记得修改接口ip
const response = await fetch('http://你的服务器IP:8001/test');评论正在加载……若这句话一直不消失,说明评论服务暂时连不上,过会儿刷新即可。
我的留言
下面这些只存在你这台设备的浏览器里 —— 换设备或清除浏览数据后就看不到了。它们只是提交成功的本地回执,不是全站可见的留言。