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. 后续非关键代码即为查询数据库
相关推荐
Coder_Boy_几秒前
基于SpringAI企业级智能教学考试平台试卷管理模块全业务闭环方案
java·大数据·人工智能·spring boot·springboot
wanghowie5 分钟前
02.01 Spring Boot|自动配置机制深度解析
android·spring boot·后端
Coder_Boy_12 分钟前
基于SpringAI的智能AIOps项目:部署相关容器化部署管理技术图解版
人工智能·spring boot·算法·贪心算法·aiops
千寻技术帮16 分钟前
10356_基于Springboot的老年人管理系统
java·spring boot·后端·vue·老年人
wanzhong233321 分钟前
开发日记2-创建http文件测试http接口
网络·网络协议·http
Qiuner28 分钟前
Spring Boot 全局异常处理策略设计(一):异常不只是 try-catch
java·spring boot·后端
MoonPointer-Byte32 分钟前
MoonReader:基于 SpringBoot 3.4 & React 的沉浸式协作阅读平台
spring boot·后端·react.js
猫吻鱼34 分钟前
【项目实践09】【基于 Websocket 的同步请求调用】
spring boot·websocket
怕浪猫9 小时前
第一章 JSX 增强特性与函数组件入门
前端·javascript·react.js
一线大码10 小时前
SpringBoot 3 和 4 的版本新特性和升级要点
java·spring boot·后端