1

When I try to fetch data from the UserController I get returned Html for some reason. It is the index.html file under the React > Public folder. It should be returning the Users from the UserController.

I have a React frontend app which I have added ASP.NET Core Web API backend. https://learn.microsoft.com/en-us/visualstudio/javascript/tutorial-asp-net-core-with-react?view=vs-2022

The browser URL is https://localhost:3000/

The backend, ASP.NET Core Web API, App URL is (found under Properties > Debug) https://localhost:7015;http://localhost:5015

This is what is returned

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="/logo192.png" />
    <!--
      manifest.json provides metadata used when your web app is installed on a
      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
    -->
    <link rel="manifest" href="/manifest.json" />
    <!--
      Notice the use of  in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>React App</title>
  <script defer src="/static/js/bundle.js"></script></head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
  </body>
</html>

My fetch code - I am returning .text() instead of .json() because obviously it results in an error because json is not returned but html.

    useEffect(() => {

        const fetchUsers = async () => {

            const result = await fetch('https://localhost:3000/api/user');
            const usersText = await result.text();
            console.log(usersText)
        }

        fetchUsers();
    }, [])

If I return .json() instead of .text() I get the following error, because obviously html is returned.

Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

UserController.cs

using Microsoft.AspNetCore.Mvc;

namespace ASPNETCore_Backend.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        [HttpGet]
        public ActionResult<IEnumerable<User>> List()
        {
            // in real life - retrieve from database
            var users = new List<User>{
                new User {
                    Id = 1,
                    Name = "Jon Hilton",
                    Summary = "36 / Lead Software Developer" }
            };

            return Ok(users);
        }
    }

    public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Summary { get; set; }
    }
}

Update - I have added AddCors() to Program.cs

builder.Services.AddCors(options =>
{
    options.AddPolicy("CORSPolicy", 
        builder =>
        {
            builder
            .AllowAnyMethod()
            .AllowAnyHeader()
            .WithOrigins("https://localhost:3000");
        });
});
code above...
app.UseHttpsRedirection();
app.UseCors("CORSPolicy"); // Added
app.UseStaticFiles();
code below...

and updated the fetch code to

const result = await fetch('https://localhost:7015/api/user');

but no luck, still get an error, though at least it doesn't return the Html file.

GET https://localhost:7015/api/user 404

17
  • What is the error? Commented Jan 3, 2022 at 1:30
  • Well, if I return .json() instead of .text() I get "Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0" because the Html file is returned instead. Commented Jan 3, 2022 at 1:32
  • How do you run the project? It seems like your .NET backend is returning the react public HTML file Commented Jan 3, 2022 at 1:33
  • The "error" is that I have no idea why it's returning this html file, when it should be returning the Users from the UserController. Commented Jan 3, 2022 at 1:36
  • @evolutionbox how do I run the project? I just press ctrl+f5 in visual studio. I mean, I followed the Microsoft tutorial in how to set it up, how to connect React with ASP.NET Core Web API. Commented Jan 3, 2022 at 1:41

2 Answers 2

2

Firstly, you should make sure if the api url is correct, using tools like postman or using any browswer to call https://localhost:7015/api/user and make sure the api can be accessed directly.

And I think you can try builder.AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin(); for test instead because my react app has a default url http://localhost:3000 but not http.

At last, check if your react code is right:

componentDidMount() {
    fetch('https://localhost:44304/api/user')
        .then(response => response.json())
        .then(data => {
          console.log(data);
        });
  }

it worked in my side

enter image description here

============================Update===================================

Follow the tutorial you provide, and do the first 3 steps :

enter image description here

Then I get a solution within 2 projects(one react and one asp.net core 6 web api project)

Adding a controller with your code then I can access the api with url https://localhost:7119/api/user in the browser.

Modify the App.js file in the react project, adding the fetch method in the componentDidMount() function. Then start both the project.

Sign up to request clarification or add additional context in comments.

4 Comments

I called 'localhost:7015/api/user' in the browser and got "This localhost page can’t be found No webpage was found for the web address: localhost:7015/api/user HTTP ERROR 404" Browser console: "Failed to load resource: the server responded with a status of 404 ()" "crbug/1173575, non-JS module files deprecated."
then how you create your api project? I test in my side with a newly created asp.net core web api project, and create a new controller with your code. And I can access the api with pressing f5 in the visual studio.
The same way you did, I believe. I just followed the Microsoft tutorial learn.microsoft.com/en-us/visualstudio/javascript/…
I test the tutorial in my side, and I followed all the steps before this section, now I have 2 projects in one solution, then I create a new controller and copied your code. Then I start the application, and I can call the api successfully.
2

just fix your action route, API controller doesn't support any REST

[Route("~/api/user/getList")]
public ActionResult<IEnumerable<User>> List()

and make the same fetch route

htt.../api/user/getList

2 Comments

Happy new year sir, your reputations increased quickly. And about this case, I test in my side followed the tutorial provided by OP and it really worked for me, so if it's necessary here to change the Route for the method? Thanks for your reply in advance.
@TinyWang. Happy New Year to you too. It depends on how many actions OP is going to have in the controller. If it is only the one as it is now , he can put attribute "~/api/user" instead of "~/api/user/getList " and be happy. But I don't think that it makes much sense to have just a list of user. I guess he is going to have CRUD at least, so it is better to start to give the meaninigfull names for the routes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.