实现vue项目和springboot项目前后端数据交互

编程入门 行业动态 更新时间:2024-10-23 21:34:16

实现vue<a href=https://www.elefans.com/category/jswz/34/1771421.html style=项目和springboot项目前后端数据交互"/>

实现vue项目和springboot项目前后端数据交互

1、安装node.js

  • 太高版本的win7不支持
    这里安装node-v12.16.2-x64.msi,指定安装位置后直接按下一步就可以。
  • npm是node内置的工具
    这里配置npm的镜像cnpm(提高下载速度,以后用到npm的命令都可以用cnpm命令替换)不指定cnpm版本使用如下命令会报错:
npm install -g cnpm --registry=
  • 错误信息:
npm WARN notsup Unsupported engine for npm-normalize-package-bin@3.0.1: wanted:{"node":"^14.17.0 || ^16.13.0 || >=18.0.0"} (current: {"node":"12.16.2","npm":"6.14.4"})
npm WARN notsup Not compatible with your version of node/npm: npm-normalize-package-bin@3.0.1
  • 检查错误,参照网上的对应版本图,node12要用cnpm 6版本,输入如下命令:
npm install -g cnpm@6 --registry=

  • 查看node和npm版本
node -v
npm -v

2、安装vue-cli脚手架

  • vue-cli是在node基础上构建的工具,而vue-cli又可以快速搭建含vue功能的模块(即模块化开发)。安装vue-cli 3.x脚手架命令如下:
cnpm install @vue/cli -g
  • 查看版本
vue -V

3、创建vue项目

vue-cli脚手架创建的是模块化项目,使用模块化开发(.vue后缀的文件为单文件组件,一个文件里封装了html、js、css代码)。项目属于单页面应用(SPA),通过路由跳转链接,不利于SEO(爬虫抓取不到内容),可以用Nuxt框架解决该问题(这是后话)。所以说vue比较适合做后台管理系统。但前端分离的插拔特性,可以让它方便地切换为移动端浏览器、app或小程序。

  • 这里有两种方法创建,第一种是用命令(会在当前文件夹下创建文件夹):
vue create 项目名 
  • 第二种用UI可视化界面创建:
vue ui

启动vue可视化工具,会在浏览器中打开,创建过项目的需要返回主页:



选手动配置



点创建即可。

这里不保存预设。

等待安装完,来到欢迎界面就可以就可以关闭网页了,后期安装其它插件我们可以通过命令行执行,也很方便。

  • 进入项目文件夹下,cmd执行命令启动项目
cd 项目文件夹名
npm run serve

运行后,显示如下,在浏览器中输入其中一个地址即可看到欢迎界面,说明vue项目成功跑起来了。

4、数据交互的准备工作

这里默认你已经懂得vue编码的一些基础知识,由于缩减篇幅,所以在此只会贴上关键代码。

前后端分离的项目,要进行数据交互,我们使用的是异步请求工具,JS使用的是Ajax,而vue使用的是axios

  • 安装axios插件:
cnpm install axios -S
cnpm i vue-axios -S

5、前后端数据交互之前端

前后端人员协商会有接口文档,我们以登录和注册为例:

  • 登录请求
//发送get请求 查询用户(用post更安全,这里只是举例使用方法)this.axios.get("http://localhost:80/api/user/login",{params:{"username":username,"password":password}}).then(resp => { //数据传输成功//用户名密码正确if(resp.data.data_status === 0){//路由跳转router.push("/")}else{//显示失败消息,可能是用户名或密码错误ElMessage({message:resp.data.data.message,duration:1000,type:"error"})}							}).catch(error => { //数据传输失败console.log(error)})
  • 注册
//访问后台保存用户(注册)this.axios.post("http://localhost:80/api/user/register",{"username":username,"email":email,"password":password}).then(function(response){//发送成功,接受返回注册状态信息if(response.data.data_status === 0){//注册成功,路由跳转							router.push("/login")}else{//显示注册失败,用户已存在ElMessage({message:response.data.data.message,duration:1000,type:"error"})}}).catch(function(response){alert("数据传输失败")})
  • 注意,这里的data_status、data.message是由后端返回的数据决定的,名称要与后端设定的返回值一致,可以先用console.log(response)查看一下返回的数据。

6、前后端数据交互之后端

  • GET提交:请求的数据会附在URL之后,在地址栏显示出来;POST提交:把提交的数据放置在是 HTTP 包的包体(请求体)中。地址栏不会改变。
  • 后端Get不要在参数加@RequestBody,因为请求是在url里中传参
    Post要在参数加@RequestBody,因为是在请求体中取值
  • 后端登录
	//后端登录@GetMapping("/api/user/login")@ResponseBody//使用ajax时必须加,会把返回类转化为json  Get不要加@RequestBody,是在url里中传参public CommonResult<Message> loginVue(User user){//注册用户逻辑int data_status = userService.loginVue(user);if (data_status == 0) {return CommonResult.success(Message.createMessage("注册成功"));} //实际开发中的状态码举例:   10001 用户已存在  10002 用户名或密码错误  20001 商品已存在 。。。else if(data_status == 2){return CommonResult.failed(data_status, Message.createMessage("用户名或密码错误!!!"));}else {return null;}}
  • 后端注册
	@PostMapping("/api/user/register")@ResponseBody//使用ajax时必须加,会把返回类转化为json  Post要加@RequestBody,是在请求体中取值public CommonResult<Message> registerVue(@RequestBody User user){//System.out.println(username);
//		System.out.println(user);//注册用户逻辑int data_status = userService.registerVue(user);if (data_status == 0) {return CommonResult.success(Message.createMessage("注册成功"));			} else {return CommonResult.failed(data_status, Message.createMessage("用户名或邮箱已存在,请更改信息!!!"));}}

Get请求不要在参数前加@RequestBody,Post请求要在参数前加@RequestBody。重要的事情说三遍!!!

这样就可以直接使用User user参数来接受值

  • 后端登录还是注册都会有返回值,类名可以自定义,但类里的属性名称定义要和接口文档一致,这样前端接收到对应的值。这里我们定义了一个泛型的CommonResult<Message>。
package com.zzz.login_demo.utils;public class CommonResult<T> {private Integer data_status;private T data;protected CommonResult() {}protected CommonResult(int data_status, T data){this.data_status = data_status;this.data = data;}//返回成功(不带data信息)public static CommonResult<Object> success() {return new CommonResult<Object>(0, null);}//返回成功(带data信息)public static <T> CommonResult<T> success(T data) {return new CommonResult<T>(0, data);}//返回失败(带data信息)public static <T> CommonResult<T> failed(int data_status, T data) {return new CommonResult<T>(data_status, data);}//get/set...
}
package com.zzz.login_demo.utils;public class Message {private String message;protected Message() {}public Message(String message) {super();this.message = message;}public static Message createMessage(String message) {return new Message(message);}//get/set...}
  • 测试前后端数据交互时报错:Access-Control-Allow-Origin
Access to XMLHttpRequest at 'http://xxx' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

这是跨域请求出错,可以在前端或后端配置跨域请求。
感觉添加后端配置跨域请求比较方便,在每个Controller类的注解@Contoller的下一行添加注解@CrossOrigin即可。

7、扩展

vue项目如何部署到服务器?(Nginx)
前端、后端分开开发时如何模拟用假数据测试?(mockjs、postman)
感兴趣的童靴可以留言给我,我会安排写作。

更多推荐

实现vue项目和springboot项目前后端数据交互

本文发布于:2023-12-05 18:29:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1664958.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:项目   后端   数据   vue   springboot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!