记一次简单的前后端交互实现。使用Vue+Axios+SpringBoot+Mybatis+Mysql

1 篇文章 0 订阅

摘要:
使用Vue+Axios+SpringBoot+Mybatis+Mysql实现的前后端交互实现。实现前端向后端请求数据。
具体流程为:前端发送请求request,后端Controller层接收请求,调用Service服务进行逻辑处理,Service调用Mapper进行数据库查询并返回,最后后端向前端返回数据,前端将数据展示在页面上。

一、创建数据库、表、插入数据

CREATE DATABASE IF NOT EXISTS vue_springboot;

CREATE TABLE IF NOT EXISTS t_user (
	id INT PRIMARY KEY,
    name VARCHAR(255)
);

INSERT INTO t_user (id, name)
VALUES (1,'张三');

二、创建后端项目

使用Spring Boot + Mybatis + Druid

1.引入依赖

修改pom.xml

<dependencies>

        <!--spring-boot通用依赖模块-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.7.5</version>
        </dependency>
        <!-- 德鲁伊数据库连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.16</version>
        </dependency>
        <!--mysql连接驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.26</version>
        </dependency>
    	<!--Lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.24</version>
        </dependency>
    	<!--Mybatis依赖-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>
    </dependencies>
2.修改Spring Boot配置
server:
  port: 8080

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/vue_springboot?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
    username: root
    password: abc123.
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
3.创建User的pojo类
@Data
public class User {
    private Long id;
    private String name;
}
4.创建Controller、Service、Mapper

UserController

@Slf4j
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/user")
    public User getUser(Long id) {
        User user = userService.getUser(id);
        return user;
    }
}

UserService

public interface UserService {
    User getUser(Long id);
}

UserServiceImpl

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public User getUser(Long id) {
        User user = userMapper.getUserById(id);
        return user;
    }
}

Mapper

@Mapper
public interface UserMapper {
    @Select("select * from t_user where id = #{id}")
    User getUserById(Long id);
}
5.跨域资源共享配置springboot的配置类
@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:5173")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("*");
    }
}

不设置这一步的话为前端控制台会报错:Access to XMLHttpRequest at ‘http://localhost:8080/user?id=1’ from origin ‘http://localhost:5173’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

这是因为在所请求的资源上没有设置’Access-Control-Allow-Origin’响应头,导致浏览器阻止了跨域请求。

CORS是一种浏览器安全机制,用于限制跨域请求。默认情况下,浏览器只允许从相同源(协议、域名和端口相同)发起的请求。当请求涉及不同源时,浏览器会发送预检请求(OPTIONS请求)以确定服务器是否允许跨域访问。服务器需要在响应中包含适当的CORS头信息,如’Access-Control-Allow-Origin’,以允许来自其他源的请求。

完成之后,启动后端工程:http://localhost:8080

三、创建前端项目

Vue + Axios

初始一个Vue项目,运行命令npm create vite@latest 输入项目名,选择Vue项目,其他默认就好。

安装axios :npm install axios

编写App.vue

<template>
  <div>
    <p>{{responseData}}</p>
  </div>
</template>

<script>
import axios from 'axios';
export default {
  data() {
    return {
      responseData: null
    };
  },
  mounted() {
    axios.get('http://localhost:8080/user?id=1')
        .then(response => {
          // 响应成功时的处理
          this.responseData = response.data;
          console.log(response)
        })
        .catch(error => {
          // 响应错误时的处理
          console.error(error);
        });
  }
};
</script>

<style scoped>
</style>

运行命令npm run dev启动前端项目

打开页面显示{ “id”: 1, “name”: “张三” }

这就实现了一个简单的前后端交互项目

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值