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 小时前
SpringBoot项目的五种创建方式
java·spring boot·后端
Java后端的Ai之路6 小时前
14、ReactJS - 路由(Router)
前端·react.js·状态模式
古法老登瞎折腾9 小时前
大数据智能运维实战(一):机器和任务数据都有了,如何用 MCP 搭建运维助手?
大数据·运维·spring boot·spring ai·mcp
企业数字化笔记10 小时前
多租户配额怎么控制?用量口径、并发预留与超额处理的实现方法
java·数据库·spring boot
鶴哥只手遮天10 小时前
React 19.3.1 源码深度剖析-第 12 章(下)RSC 与 Flight 协议
前端·react.js·开源
flash俊杰11 小时前
给工具调用划安全红线:SSRF 防护、逐跳复检与沙箱取舍
http
WeiXin_DZbishe12 小时前
基于springboot装修风格选择系统的设计与开发-计算机毕设【课程设计】77964
java·vue.js·spring boot·后端·python·php·课程设计
HelloWorld00113 小时前
别再手写 fetch 了!用 Next.js 14 + SSE 打造媲美 ChatGPT 的生产级 AI 流式聊天前端(全套代码+避坑实战)
react.js
鸿蒙开发13 小时前
扫描 PDF 看得见却搜不到?用 Tesseract.js + PDF.js 生成可搜索 PDF
前端·react.js
十年Java程序媛13 小时前
Java 多线程基础与锁机制详解|进程线程、锁升级、synchronized 与 Lock 对比
java·开发语言·spring boot