我正在尝试创建一个应用程序,其中客户端前端使用react.js 制作,后端使用ASP.Net Core MVC。我正在尝试从 api 获取数据以呈现该表的所有数据,但它返回的是 html 文件,而不是 json 文件。
这是反应代码:
import React, { useState, useEffect } from 'react';
import { AllBlogCard } from '../components/AllBlogCard.jsx';
import axios from 'axios';
const PostsPage = () => {
const [blogPosts, setBlogPosts] = useState([]);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch('/api/BlogApi/List');
if (response.ok) {
const data = await response.json();
console.log('blog data:', data);
setBlogPosts(data);
} else {
console.error('Failed to fetch blog posts');
}
} catch (error) {
console.error(error);
}
};
fetchData();
}, []);
return (
<div className="container mt-5">
<div className="row">
<div className="col-lg-8 mx-auto">
<h2 className="section-heading text-center mb-4">All Blog Posts</h2>
{blogPosts.map((post, index) => (
<AllBlogCard key={index} {...post} />
))}
<div className="text-center mt-4">
<button className="btn customBtn my-5">View More Posts<i className="bi bi-arrow-down m-1"></i></button>
</div>
</div>
</div>
</div>
);
};
export default PostsPage;
这是后端API方法:
[Route("api/[controller]")]
[ApiController]
public class BlogApiController : ControllerBase
{
private readonly BloggieDbContext _context;
private readonly IBlogPostRepo blogPostRepo;
public BlogApiController(IBlogPostRepo blogPostRepo, BloggieDbContext context)
{
_context = context;
this.blogPostRepo = blogPostRepo;
}
[HttpGet("List")]
[Produces("application/json")]
public async Task<IActionResult> ListApi()
{
var blogPosts = await blogPostRepo.GetAllAsync();
return Ok(blogPosts);
}
}
对于上下文,博客文章存储库来自存储库模式文件夹,它具有
DbContext
以及正确呈现数据所需的一切。