- 写一个最简单的组件
import React, { useState, useEffect } from 'react';
function StudentQuery() {
const [studentName, setStudentName] = useState('');
const [response, setResponse] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const url = new URL('http://localhost:8080/student');
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();
setResponse(data);
console.log(data);
} catch (err) {
setError(err.message);
}
};
if (studentName) {
fetchData();
}
}, [studentName]);
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;
- 后端controller层代码
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;
@CrossOrigin(origins = "http://localhost:3000")
@GetMapping(value = "/student", produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody Student getStudentByName(@RequestParam String name) {
return studentService.getStudentByName(name);
}
}
- 后续非关键代码即为查询数据库