最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Unable to fetch from controller - Reactasp.net core Web API - Stack Overflow

programmeradmin1浏览0评论

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.

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 /
    -->
    <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

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./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./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

Share Improve this question edited Feb 1, 2022 at 14:14 Serge 44k4 gold badges26 silver badges52 bronze badges asked Jan 3, 2022 at 1:26 JAmesJAmes 2811 gold badge5 silver badges18 bronze badges 17
  • What is the error? – evolutionxbox 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. – JAmes 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 – evolutionxbox 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. – JAmes 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. – JAmes Commented Jan 3, 2022 at 1:41
 |  Show 12 more ments

2 Answers 2

Reset to default 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:

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

it worked in my side

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

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

Then I get a solution within 2 projects(one react and one asp 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 ponentDidMount() function. Then start both the project.

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
发布评论

评论列表(0)

  1. 暂无评论