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. 后续非关键代码即为查询数据库
相关推荐
Uranus^1 分钟前
深入解析Spring Boot与Kafka集成:构建高性能消息驱动应用
spring boot·kafka·消息队列·分布式系统
悄悄地努力1 小时前
IDEA 新建 SpringBoot 项目时,没有高版本 SpringBoot 可选
java·spring boot·intellij-idea
Hello.Reader2 小时前
ngx_http_proxy_protocol_vendor_module 模块
网络协议·http·flask
Hello World......5 小时前
Java求职面试揭秘:从Spring到微服务的技术挑战
大数据·hadoop·spring boot·微服务·spark·java面试·互联网大厂
chenbin___5 小时前
react native text 显示 三行 超出部分 中间使用省略号
javascript·react native·react.js
Hello World......5 小时前
互联网大厂Java面试:从Spring到微服务的全面探讨
java·spring boot·spring cloud·微服务·面试·技术栈·互联网大厂
拾贰_C6 小时前
【SpringBoot】MyBatisPlus(MP | 分页查询操作
java·spring boot·后端·spring·maven·apache·intellij-idea
shykevin8 小时前
python开发Streamable HTTP MCP应用
开发语言·网络·python·网络协议·http
Uranus^9 小时前
深入解析Spring Boot与JUnit 5的集成测试实践
spring boot·单元测试·集成测试·junit 5·mockito
purrrew11 小时前
【Java ee初阶】HTTP(2)
网络·网络协议·http