react项目通过http调用后端springboot服务最简单示例

  1. 写一个最简单的组件
js 复制代码
import React, { useState, useEffect } from 'react';

function StudentQuery() {
  const [studentName, setStudentName] = useState(''); // 存储学生的姓名
  const [response, setResponse] = useState(null); // 存储从服务器获取的响应数据
  const [error, setError] = useState(null); // 存储错误信息

  // 当studentName发生变化时,自动发起请求
  useEffect(() => {
    const fetchData = async () => {
      try {
        const url = new URL('http://localhost:8080/student'); // 替换为实际的API地址
        console.log(url);
        url.searchParams.append('name', studentName); // 添加查询参数

        const response = await fetch(url); 
        console.log(response);
        
        if (!response.ok) {
          console.log(response);
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json(); // 假设服务器返回JSON格式的数据
        setResponse(data);
        console.log(data);
      } catch (err) {
        setError(err.message);
      }
    };

    if (studentName) {
      fetchData();
    }
  }, [studentName]); // 依赖数组,只有当studentName改变时才会触发useEffect

  return (
    <div>
      <input
        type="text"
        placeholder="Enter student name"
        value={studentName}
        onChange={(e) => setStudentName(e.target.value)}
      />
      {response && <p>Response: {JSON.stringify(response)}</p>}
      {error && <p style={{ color: 'red' }}>Error: {error}</p>}
    </div>
  );
}

export default StudentQuery;
  1. 后端controller层代码
java 复制代码
package com.example.demo2.controller;

import com.example.demo2.model.Student;
import com.example.demo2.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

@RestController
public class StudentController {
    @Autowired
    private StudentService studentService;

    // 在 Spring MVC 的控制器方法中,如果返回Student对象,确保方法的返回类型和@RequestMapping(或者@GetMapping、@PostMapping等注解)中的produces属性设置正确
    @CrossOrigin(origins = "http://localhost:3000") // 解决浏览器跨来源资源共享限制,否则响应结果前端收不到
    @GetMapping(value = "/student", produces = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody Student getStudentByName(@RequestParam String name) {
        return studentService.getStudentByName(name);
    }
}
  1. 后续非关键代码即为查询数据库
相关推荐
红豆和绿豆6 小时前
如何发起http的请求,在系统中集成
网络·网络协议·http
李长渊哦6 小时前
使用Druid连接池优化Spring Boot应用中的数据库连接
数据库·spring boot·后端
web135085886356 小时前
【Spring Boot】Spring AOP动态代理,以及静态代理
spring boot·后端·spring
尚学教辅学习资料8 小时前
基于SpringBoot的图书借阅小程序+LW参考示例
spring boot·后端·小程序·java毕设·图书借阅
一 乐8 小时前
高校体育场管理系统系统|体育场管理系统小程序设计与实现(源码+数据库+文档)
前端·javascript·数据库·spring boot·高校体育馆系统
山海不说话8 小时前
从零搭建微服务项目Base(第5章——SpringBoot项目LogBack日志配置+Feign使用)
spring boot·后端·spring·spring cloud·微服务·logback
不良人天码星9 小时前
Redis的简单使用
java·spring boot·redis·mybatis
初尘屿风9 小时前
小程序类毕业设计选题题目推荐 (29)
spring boot·后端·学习·微信·小程序·课程设计
qq_124987075310 小时前
Java+SpringBoot+数据可视化的家庭记账小程序(程序+论文+安装+调试+售后等)
java·spring boot·小程序·毕业设计
WCL-JAVA10 小时前
docker安装kafka,并通过springboot快速集成kafka
spring boot·docker·kafka