1.conf配置
server {
listen 8088;//nignx监听的端口
server_name localhost;
前端和后端不能用同一个端口(举例:12306,去哪儿,携程前端页面不同,但都能买同一个数据库里的车票)
# 路径配置
location / {//localhost:8088/ 如果路径后什么都不写,则默认跳转到index.html文件,路由会跳转到主页面
# 相对路径配置,基于nginx启动的位置
root D:/git/dataanalyzer2/express/dataweb/dist;//前端vue(npm run build)打包之后的文件根目录
index index.html;
}
# 后端接口,反向代理
location /api/ {如果请求的路径是api
# 反向代理
proxy_pass http://localhost:80/;/后端监听80 端口
}
}
2.proxy配置
npm run dev 之后localhost:8000 直接打开就是主页面 代替了nignx功能
export default defineConfig({
plugins: [vue()],
server: {
host: "0.0.0.0",
proxy: {
'/api': {
target: 'http://127.0.0.1:8082/',//api开头的请求指向8082
changeOrigin: true
}
}
}
})
3.springboot配置
UserController
@PostMapping(value = "/add") value与前端请求路径要一致 ;get/post与前端一致
@ResponseBody
public String saveUser(HttpServletRequest request) {
User user = new User();
user.setName(request.getParameter("name")); //form表单数据
user.setPassword(request.getParameter("password"));
user.setCreateDate(new Date());
return userService.saveUser(user)==1?"SUCCESS":"FAIL";
}
4.前端axios请求
methods: {
async submit() {
let name = this.user.username;
let word = this.user.password;
// let result = await HttpUtilBase.tryDoGet(
// "/api/add?" + "username=" + name + "&" + "password=" + word,
// 100000,
// 3
// );
// let data = { "username": name, "password": word };(json字符的写法)
let formData = new FormData();
formData.append("name", name);
formData.append("password", word);
let result = await axios.post("/api/add", formData);
//form表单数据提交
this.user = result.data;
if (result.data.length == 1) {
console.log("注册成功");
}
},
},