简体   繁体   English

无法从 controller 获取 - React/asp.net 核心 Web API

[英]Unable to fetch from controller - React/asp.net core Web API

When I try to fetch data from the UserController I get returned Html for some reason.当我尝试从 UserController 获取数据时,由于某种原因,我返回 Html。 It is the index.html file under the React > Public folder.它是 React > Public 文件夹下的index.html文件。 It should be returning the Users from the UserController.它应该从 UserController 返回用户。

I have a React frontend app which I have added ASP.NET Core Web API backend.我有一个 React 前端应用程序,我添加了 ASP.NET Core Web API 后端。 https://docs.microsoft.com/en-us/visualstudio/javascript/tutorial-asp-net-core-with-react?view=vs-2022 https://docs.microsoft.com/en-us/visualstudio/javascript/tutorial-asp-net-core-with-react?view=vs-2022

The browser URL is https://localhost:3000/浏览器 URL 是https://localhost:3000/

The backend, ASP.NET Core Web API, App URL is (found under Properties > Debug) https://localhost:7015;http://localhost:5015 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.我的获取代码- 我正在返回.text() 而不是.json(),因为显然它会导致错误,因为 json 没有返回,而是 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.如果我 return.json() 而不是 .text() 我得到以下错误,因为显然 html 被返回。

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

UserController.cs用户控制器.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更新- 我已将 AddCors() 添加到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.但没有运气,仍然会出错,但至少它不会返回 Html 文件。

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

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

If it worked fine, it should look like this, if not pls add details about it:如果它工作正常,它应该看起来像这样,如果不是,请添加有关它的详细信息:

在此处输入图像描述

And I think you can try builder.AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin();而且我认为您可以尝试builder.AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin(); for test instead because my react app has a default url http://localhost:3000 but not http .改为测试,因为我的反应应用程序有一个默认的 url http://localhost:3000但没有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它在我身边有效

在此处输入图像描述

just fix your action route, API controller doesn't support any REST只需修复您的操作路线,API controller 不支持任何 REST

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

and make the same fetch route并制作相同的获取路线

htt.../api/user/getList

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用提取将JavaScript中的FormData发送到ASP.NET Core 2.1 Web API - How to send FormData from javascript to ASP.NET Core 2.1 web API using fetch 从ASP.NET页中的Web Api Controller获得价值 - Get value from Web Api Controller in ASP.NET page 将表单数据从 React 发送到 ASP.NET Core API - Send form data from React to ASP.NET Core API Installing asp.net mvc excel file and asp.net core web api forwarding via mvc controller - Installing asp.net mvc excel file and asp.net core web api forwarding via mvc controller 从 ASP.NET CORE Web Api 获取 React 中的特定响应标头(例如,Content-Disposition) - Get a specific response header (e.g., Content-Disposition) in React from an ASP.NET CORE Web Api 无法使用JavaScript将HTTP POST请求发送到ASP.NET Web API Controller - Unable to send a http POST request to ASP.NET web api Controller using javascript 如何向ASP.Net Core API控制器提交表单 - How to submit a form to an ASP.Net Core API Controller 如何从 JS 获取和保存令牌中获取 ASP.NET Web Api 令牌(登录) - How to grab ASP.NET Web Api token (login) from a JS fetch and save token 调用 ASP.NET Core 2.2 Web API 时本地 Javascript 提取发布请求失败。 CORS 已启用 - Local Javascript Fetch Post Request Fails with call to ASP.NET Core 2.2 Web API. CORS is enabled 无法将来自 Joke API 服务器的响应渲染到视图 ASP.NET Core 5.0 MVC - Unable to render the response from the Joke API server to the view ASP.NET Core 5.0 MVC
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM