vue基础——java程序员版(vue和spingboot前后端交互)

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

​ 现在的项目大部分都是前后端分离项目,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>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值