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. 后续非关键代码即为查询数据库
相关推荐
万亿少女的梦16813 分钟前
基于SpringBoot的在线考试管理系统设计与实现
java·spring boot·后端
下次再写1 小时前
【Redis实战】深入理解Redis缓存策略:从原理到Spring Boot实践
java·spring boot·redis·缓存穿透·缓存击穿·分布式缓存·缓存策略
wordbaby1 小时前
如何封装一个生产级的 React Native 分页列表 Hook
前端·react native·react.js
小白君6531 小时前
互联网大厂Java面试:从Spring Boot到微服务的技术场景深度解析
spring boot·redis·微服务·消息队列·java面试·数据库优化
花间相见2 小时前
【全栈开发03】—— curl 常用参数详解与 HTTP 请求实战
网络·网络协议·http
imuliuliang2 小时前
五大编程语言核心对比:特性与应用全解析
运维·spring boot·nginx
ahauedu3 小时前
流水账债务
spring boot
天草二十六_简村人3 小时前
对接AI大模型之nginx代理配置SSE接口
运维·网络·nginx·http·阿里云·ai·云计算
M ? A3 小时前
Vue 转 React | VuReact 实时监听开发指南
前端·vue.js·后端·react.js·面试·开源·vureact
报错小能手4 小时前
HTTP/2 牛逼在哪?
网络·网络协议·tcp/ip·http