现在的项目大部分都是前后端分离项目,Axios是前后端交互的重要工具。
1、后端(springboot)
(1)Controller
分别是post和get请求都有Rustful路径参数value,post是User作为json格式的请求体,get是两个路径参数。
@RestController
@RequestMapping("test/")
public class MyController {
@PostMapping("/first/{value}")
public String test(@PathVariable String value,@RequestBody User user){
return value+" "+user.username+" "+user.password;
}
@GetMapping("/first/{value}")
public String test(@PathVariable String value,String username,String password){
return value+" "+username+" "+password;
}
}
(2)实体类(User)
User不要忘了给属性以set方法。
@Data
class User implements Serializable {
String username;
String password;
}
2、前端
(1)配置代理解决跨域问题
跨域的本质就是浏览器基于同源策略的一种安全手段。所谓同源就是必须有以下三个相同点:协议相同、域名相同、端口相同。如果其中有一项不同,即出现非同源请求,就会产生跨域。
浏览器跨域机制的主要目的是保护用户的安全和隐私。
修改vue.config.js 配置代理,此后我们的请求只需要用/api 代替http://localhost:8080 即可
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
// 修改前端端口号
devServer: {
port: 7070,
//配置代理
proxy: {
//api 是个请求时的前缀,请求到/api转发到http://localhost:8080,此后只需要在所有前端请求路径上
//http://localhost:前端端口号/api等于http://localhost:后端端口号
'/api': {
target: 'http://localhost:8080',
//因为路径出现了/api所以需要取消
pathRewrite: {
'^/api': ''
}
}
}
},
// 关闭eslint校验
lintOnSave: false
})
(2)请求方式一
向后端返送post请求,并添加请求体(后端接收的是json格式)。不要忘记引入axiosimport axios from "axios"
<template>
<div>
账号:<input type="text" v-model="username"/> <br/>
密码:<input type="password" v-model="password"/>
<button @click="submit">提交</button>
</div>
</template>
<script>
import axios from "axios";
export default {
data() {
return {
password: '',
username: ''
}
},
methods:{
submit(){
let _this=this;
//发送http请求,post
axios.post("/api/test/first/login",{
username: _this.username,
password: _this.password
}).then(res=> {
console.log(res.data)
}).catch(error=>{
console.log("错误: "+error.message)
})
}
}
}
</script>

(3)请求方式二
通用写法,method规定请求方式,这个是向后端返送get请求,并添加路径参数。不要忘记引入axiosimport axios from "axios"
<template>
<!--Axios通用写法-->
<div>
账号:<input type="text" v-model="username"/> <br/>
密码:<input type="password" v-model="password"/>
<button @click="submit1">提交</button>
</div>
</template>
<script>
import axios from "axios";
export default {
data() {
return {
password: '',
username: ''
}
},
methods:{
submit1(){
let _this=this;
axios({
url:'/api/test/first/login',
// `method` 是创建请求时使用的方法
method: 'get', // 默认就是get
/**
* headers:'',//请求头,可以放token
*/
// `params` 是即将与请求一起发送的 URL 参数
// 一般是get请求,也就是路径参数
params: {
username: _this.username,
password: _this.password
},
// data是请求体,post、put、delete用,get没有请求体不用
/**
* data: {
* firstName: 'Fred'
* },
*/
}).then(res=>{
console.log(res.data)
}).catch(err=>{
console.log(err.message)
})
}
}
}
</script>

本文介绍了如何在前后端分离的项目中,使用SpringBoot的Controller处理POST和GET请求,以及如何通过Vue的axios库配置代理解决跨域问题,包括POST请求体的设置和GET请求路径参数的传递。
4万+

被折叠的 条评论
为什么被折叠?



