I’m trying to create an app where the frontend on the client side is made with react.js and the backend uses ASP.Net Core MVC. I’m trying to fetch the data from the api for rendering all the data for that table, but instead of a json file it’s returning an html file.
This is the react code:
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;
This is the backend API method:
[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);
}
}
For context, the blogpost repo is from a repository pattern folder and it has the DbContext
and everything necessary to properly render the data.
2
Answers
I believe this is what you need to do. Set "Content-Type" in the header to "application/json"
You may test it via Postman as follows:
Firstly of all, your code in react app and controller should be correct as I test with them, everything worked well.
The controller I used is listed below, as you can see, I just return a list of model to mock the response of your
blogPostRepo.GetAllAsync();
.Based on my experience, when I got html content instead of the expected data result from an MVC controller, it always because I didn’t pass the authentication so that the app would redirect me to the login page.
I’m not sure if you are facing the same issue, my action plan is that you might visit the API through the browser since it’s a get request then see what the html contains. If this a login page, then you might make a mistake to add the authentication scheme, for API it should return 401 error instead of redirect to sign in page.
By the way, I also want to confirm that if there’s exception inside your api, adding break point to debug the project is helpful if there’s exception inside it.