Springboot+Vue前后端交互---axios

一.前端发送请求
1.导入axios

import axios from 'axios'

axios支持多种请求方式,其中常用方式如下:

axios.get(url, params).then(res => { do something })
axios.post(url, data).then(res => { do something })

.then后为回调函数,即发送成功后后端返回数据至res,则可得到res进行处理,如res.data即为后端return返回值,为获取具体内容可使用console.log(res)进行查看

二.springboot接收数据
1.预备知识
(1)在类前使用@RestController注解则函数return将为json数据,因为vue全权负责前端,因此springboot的controller类通常均需要添加此注解,且其实际为@ResponseBody与@Controller的简写形式

(2)@RequestMapping,@PostMapping,@GetMapping的区别:使用@RequestMapping注解则可接受post与get请求,@PostMapping仅接受post请求,@GetMapping注解仅接受get请求。在方法前添加此注解并声明路径,则声明路径即为访问路径,如
在这里插入图片描述
则其访问路径即为http://localhost:8080/index

2.个人常用接收方式
(1)接收get请求数据:
使用@PathVariable注解:

	@RequestMapping("/find/{articleID}")
    public Article findArticleByID(@PathVariable("articleID") String articleID){
        return articleMapper.findArticleByID(articleID);
    }

解释:
@RequestMapping("/find/{articleID}")中的{articleID}即为上传的数据值,则此时若前端想要传输值为6,则访问url为:http://localhost:8080/find/6,由于使用了@PathVariable注解,因此其值将自动传入注解后的变量,即String articleID

(2)接收post请求数据
使用@RequestBody注解:

	@RequestMapping("/addcomment")
    public Integer addComment(@RequestBody ArticleComment articleComment){
        return articleCommentMapper.addNewComment(articleComment);
    }

解释:@RequestBody将自动将传输值填充入其后的java类,且此java类通常为bean类,即其每一个属性均对应于数据表中的某一字段,注:需为bean类添加set和get方法

三.实战
前端:

submit(){
    let url = 'http://localhost:8080/add';
    axios.post(url,{userPassword:this.password,userName:this.username,email:this.email,phoneNumber:this.phone}).then(res=>{
        if(res.data == 0){
            alert('用户已存在');
            return;
        }
    })
}

后端:

	@RequestMapping("/add")
    public Integer addNewUser(@RequestBody User user){
        if(userMapper.selectUserByName(user.getUserName()) != null)
            return 0;//用户名已存在
        return userMapper.addNewUser(user);
    }

四.axios小扩展
为防止程序对框架的过度依赖,通常在一个文件内实例化axios,则在框架改变时改变此文件即可。具体做法:
创建networks文件夹,在其下创建request.js文件

import axios from 'axios'
export function request(config){
	const instance = axios.create({
		baseURL:'http://localhost:8080',
		timeout:5000
		})
		return instance(config);
}

则调用方式:

request({
	url:'/add'
	}).then(res=>{
	}).catch(err=>{
	})

此请求方式为默认为get请求,使用post请求进行发送则使用如下形式:

request({
	url:'/add',
	method:'post',
	data:configures
	}).then(res=>{
	}).catch(err=>{
})
  • 9
    点赞
  • 78
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值