[英]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.