英文:
React with ASP.NET Core not displaying data
问题
我正在学习如何将React与ASP.NET Core应用程序集成,我创建了一个新的React与ASP.NET Core项目,使用.NET 6.0和SQL Server数据库。这是我用来显示Student表内容的代码:
StudentController:
[Route("api/[controller]")]
[ApiController]
public class StudentController : ControllerBase
{
private readonly ApplicationDbContext _dbcontext;
public StudentController(ApplicationDbContext dbcontext)
{
_dbcontext = dbcontext;
}
[HttpGet]
[Route("GetStudents")]
public IActionResult GetStudents()
{
List<Student> students = _dbcontext.Student.ToList();
return StatusCode(StatusCodes.Status200OK, students);
}
}
Student.js:
import React, { useEffect, useState } from "react";
const App = () => {
// 创建 useState
const [students, setStudents] = useState([]);
// 调用 API
useEffect(() => {
fetch("api/Student/GetStudents")
.then(response => response.json())
.then(responseJson => {
setStudents(responseJson);
});
}, []);
return (
<div className="container">
<h1>Students</h1>
<div className="row">
<div className="col-12">
<table className="table table-stripped table-bordered">
<thead>
<tr>
<th>Id</th>
<th>Student Name</th>
<th>Course Enrolled</th>
</tr>
</thead>
<tbody>
{students.map(item => (
<tr key={item.Id}>
<td>{item.Id}</td>
<td>{item.Name}</td>
<td>{item.Course}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</div>
);
};
export default App;
AppRoutes.js:
import { default as Student } from "./components/Student";
const AppRoutes = [
{
path: '/students',
element: <Student />
}
];
export default AppRoutes;
问题在于这段代码没有显示来自数据库的任何数据,它只显示了表头而没有行。代码有什么问题?我漏掉了什么吗?
英文:
I'm learnig to integrate React with ASP.NET Core applications, i created a new React with ASP.NET Core project in .NET 6.0 with SQL Server database, this is the code i used to display the content of STudent table:
StudentController:
[Route("api/[controller]")]
[ApiController]
public class StudentController : ControllerBase
{
private readonly ApplicationDbContext _dbcontext;
public StudentController(ApplicationDbContext dbcontext)
{
_dbcontext = dbcontext;
}
[HttpGet]
[Route("GetStudents")]
public IActionResult GetStudents()
{
List<Student> students =_dbcontext.Student.ToList();
return StatusCode(StatusCodes.Status200OK, students);
}
}
Student.js:
import {React, useEffect, useState } from "react";
const App = () => {
//create useState
const [students, setStudents] = useState([])
//call api
useEffect(() => {
fetch("api/Student/GetStudents")
.then(response => { return response.json() })
.then(responseJson => {
setStudents(responseJson)
})
}, [])
return (
<div className="container">
<h1>Students</h1>
<div className="row">
<div className="col-12">
<table className="table table-stripped table-bordered">
<thead>
<tr>
<th>Id</th>
<th>Student Name</th>
<th>Course Enrolled</th>
</tr>
</thead>
<tbody>
{
students.map((item) => (
<tr>
<td>{item.Id}</td>
<td>{item.Name}</td>
<td>{item.Course}</td>
</tr>
))
}
</tbody>
</table>
</div>
</div>
</div>
)
}
export default App;
AppRoutes.js:
import { default as Student } from "./components/Student";
const AppRoutes = [
{
path: '/students',
element: <Student />
}
];
export default AppRoutes;
The problem is that this code didn't display any data from the database, it displays only the header of the table with no rows. What's wrong with the code? am i missing anything?
答案1
得分: 1
Please open your browser's developer tools to check for any error messages.
如果您看到图片上的错误,可能是因为您没有更改 setupProxy.js
文件(请查看 此链接)。请将您的 API 路径添加到此文件中的 context
部分:
const context = [
"/weatherforecast",
"/api/Student/GetStudents"
];
完善 setupProxy.js
文件:
const { createProxyMiddleware } = require('http-proxy-middleware');
const { env } = require('process');
const target = env.ASPNETCORE_HTTPS_PORT ? `https://localhost:${env.ASPNETCORE_HTTPS_PORT}` :
env.ASPNETCORE_URLS ? env.ASPNETCORE_URLS.split(';')[0] : 'http://localhost:59947';
const context = [
"/weatherforecast",
"/api/Student/GetStudents"
];
module.exports = function(app) {
const appProxy = createProxyMiddleware(context, {
target: target,
secure: false,
headers: {
Connection: 'Keep-Alive'
}
});
app.use(appProxy);
};
此外,请将 Student.js
文件中的 tbody
部分更改为以下内容:
<tbody>
{
students.map(item =>
<tr key={item.id}>
<td>{item.id}</td>
<td>{item.name}</td>
<td>{item.course}</td>
</tr>
)
}
</tbody>
您需要为其添加 key
属性,如果没有特殊要求,属性名称应为小写。
测试结果:
英文:
Please open your browser's developer tools to check for any error messages.
If you have the error on the picture, it's probably because you didn't change the setupProxy.js
file(check this link). Please add your Api path to the context
in this file:
const context = [
"/weatherforecast",
"/api/Student/GetStudents"
];
Complete setupProxy.js file:
const { createProxyMiddleware } = require('http-proxy-middleware');
const { env } = require('process');
const target = env.ASPNETCORE_HTTPS_PORT ? `https://localhost:${env.ASPNETCORE_HTTPS_PORT}` :
env.ASPNETCORE_URLS ? env.ASPNETCORE_URLS.split(';')[0] : 'http://localhost:59947';
const context = [
"/weatherforecast",
"/api/Student/GetStudents"
];
module.exports = function(app) {
const appProxy = createProxyMiddleware(context, {
target: target,
secure: false,
headers: {
Connection: 'Keep-Alive'
}
});
app.use(appProxy);
};
Also, change the tbody
section in Student.js
to this:
<tbody>
{
students.map(item =>
<tr key={item.id}>
<td>{item.id}</td>
<td>{item.name}</td>
<td>{item.course}</td>
</tr>
)
}
</tbody>
You need to add key
prop to it, if you didn't do something special, the property name should be lower case.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论