React与ASP.NET Core不显示数据

huangapple go评论63阅读模式
英文:

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(&quot;api/[controller]&quot;)]
[ApiController]
public class StudentController : ControllerBase
{
private readonly ApplicationDbContext _dbcontext;
public StudentController(ApplicationDbContext dbcontext)
{
_dbcontext = dbcontext;
}
[HttpGet]
[Route(&quot;GetStudents&quot;)]
public IActionResult GetStudents()
{
List&lt;Student&gt; students =_dbcontext.Student.ToList();
return StatusCode(StatusCodes.Status200OK, students);
}
}

Student.js:

import {React, useEffect, useState } from &quot;react&quot;;
const App = () =&gt; {
//create useState
const [students, setStudents] = useState([])
//call api
useEffect(() =&gt; {
fetch(&quot;api/Student/GetStudents&quot;)
.then(response =&gt; { return response.json() })
.then(responseJson =&gt; {
setStudents(responseJson)
})
}, [])
return (
&lt;div className=&quot;container&quot;&gt;
&lt;h1&gt;Students&lt;/h1&gt;
&lt;div className=&quot;row&quot;&gt;
&lt;div className=&quot;col-12&quot;&gt;
&lt;table className=&quot;table table-stripped table-bordered&quot;&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Id&lt;/th&gt;
&lt;th&gt;Student Name&lt;/th&gt;
&lt;th&gt;Course Enrolled&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
{
students.map((item) =&gt; (
&lt;tr&gt;
&lt;td&gt;{item.Id}&lt;/td&gt;
&lt;td&gt;{item.Name}&lt;/td&gt;
&lt;td&gt;{item.Course}&lt;/td&gt;
&lt;/tr&gt;
))
}
&lt;/tbody&gt;
&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
)
}     
export default App;

AppRoutes.js:

import { default as Student } from &quot;./components/Student&quot;;
const AppRoutes = [
{
path: &#39;/students&#39;,
element: &lt;Student /&gt;
}
];
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 属性,如果没有特殊要求,属性名称应为小写。

测试结果:

React与ASP.NET Core不显示数据

英文:

Please open your browser's developer tools to check for any error messages.

React与ASP.NET Core不显示数据
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 =  [
&quot;/weatherforecast&quot;,
&quot;/api/Student/GetStudents&quot;
];

Complete setupProxy.js file:

const { createProxyMiddleware } = require(&#39;http-proxy-middleware&#39;);
const { env } = require(&#39;process&#39;);
const target = env.ASPNETCORE_HTTPS_PORT ? `https://localhost:${env.ASPNETCORE_HTTPS_PORT}` :
env.ASPNETCORE_URLS ? env.ASPNETCORE_URLS.split(&#39;;&#39;)[0] : &#39;http://localhost:59947&#39;;
const context =  [
&quot;/weatherforecast&quot;,
&quot;/api/Student/GetStudents&quot;
];
module.exports = function(app) {
const appProxy = createProxyMiddleware(context, {
target: target,
secure: false,
headers: {
Connection: &#39;Keep-Alive&#39;
}
});
app.use(appProxy);
};

Also, change the tbody section in Student.js to this:

&lt;tbody&gt;
{
students.map(item =&gt; 
&lt;tr key={item.id}&gt;
&lt;td&gt;{item.id}&lt;/td&gt;
&lt;td&gt;{item.name}&lt;/td&gt;
&lt;td&gt;{item.course}&lt;/td&gt;
&lt;/tr&gt;
)
}
&lt;/tbody&gt;

You need to add key prop to it, if you didn't do something special, the property name should be lower case.

Test Result:
React与ASP.NET Core不显示数据

huangapple
  • 本文由 发表于 2023年6月8日 18:18:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76430849.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定