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. 后续非关键代码即为查询数据库
相关推荐
花千树-010几秒前
JMeter 入门与进阶指南:从零开始构建你的压测环境
java·spring boot·jmeter·性能优化·压力测试·可用性测试
Arthas21714 分钟前
互联网大厂Java面试实战:从基础到架构的渐进式考察
java·spring boot·微服务·面试·技术栈
Cxiaomu19 分钟前
像ChatGPT一样逐字输出:React + TypeScript 流式接收与“打字机”效果实现方案
人工智能·react.js·chatgpt·typescript
xxjj998a43 分钟前
spring security 超详细使用教程(接入springboot、前后端分离)
java·spring boot·spring
小江的记录本44 分钟前
【Docker】 Docker 全平台部署(Linux / Windows / MacOS)与 前后端分离项目 容器化方案
java·linux·windows·http·macos·docker·容器
crack_comet1 小时前
Spring Boot 3.5.11 分离打包(无参数启动+Jar瘦身)完整配置文档
java·spring boot·后端·maven·intellij-idea·jar
txinyu的博客1 小时前
muduo http优化 —— 在原本数据监测http上 多支持了功能完善的http_1
网络·网络协议·http
小贺儿开发1 小时前
Unity3D LED点阵屏幕模拟
http·unity·浏览器·网络通信·led·互动·点阵屏
知识汲取者1 小时前
初识 RuoYi-Vue
java·spring boot·后端·开源软件
独自破碎E2 小时前
Spring Boot + Vue 前后端联调踩坑记录
vue.js·spring boot·后端