如何使用React查询从Web API获取数据?
这可能是一个重复的问题。
我正在为前端和ASP.NET Core Web API使用React用于后端。我尝试使用React查询获取数据,但有这样的错误。
在'https:// localhost:7036/api/{控制器名称}/{action}'https:// localhost:3000'已被CORS策略阻止:no访问contescon-controlol' -Allow-Origin'Header存在于请求的资源上。
现在,我在此帖子中看到了类似的答案 访问xmlhttprequest的访问权限Localhost:3000'被CORS政策所阻止 但是,我想知道使用React Query有任何标准或优越的方法来解决此问题吗?
控制器和操作
[Route("api/[controller]")]
[ApiController]
public class GeneralController : ControllerBase {
public JsonResult GetMatureVerifyData() // Action Method
{
using(var model = new MatureVerifiedDataDTO()){
return new JsonResult(model);
}
}
}
反应查询代码
import axios from "axios";
import { useQuery } from "react-query";
export const APIcall = () => {
const { isLoading, error, } = useQuery("verify", () =>
axios.get(
"https://localhost:7036/api/General/GetMatureVerifyData"
).then((res) => console.log(res.data))
);
if (isLoading) {
console.log("Loading...");
};
if (error) {
console.log(`An error has occurred: ${error.message}`);
}
}
This may be a duplicate question.
I'm using react for frontend and asp.net core Web API for backend. I tried to fetch data using react query but got an error like this.
Access to XMLHttpRequest at 'https://localhost:7036/api/{Controller Name}/{Action}' from origin 'https://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Now, I have seen a similar answer for this error, in this post
Access to XMLHttpRequest at '...' from origin 'localhost:3000' has been blocked by CORS policy
But, I would like to know is there any standard or superior way to solve this using react query ?
Controller and Action
[Route("api/[controller]")]
[ApiController]
public class GeneralController : ControllerBase {
public JsonResult GetMatureVerifyData() // Action Method
{
using(var model = new MatureVerifiedDataDTO()){
return new JsonResult(model);
}
}
}
React Query Code
import axios from "axios";
import { useQuery } from "react-query";
export const APIcall = () => {
const { isLoading, error, } = useQuery("verify", () =>
axios.get(
"https://localhost:7036/api/General/GetMatureVerifyData"
).then((res) => console.log(res.data))
);
if (isLoading) {
console.log("Loading...");
};
if (error) {
console.log(`An error has occurred: ${error.message}`);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这不是反应问题。这是浏览器实施的安全措施。您需要启用cors 在您的ASP.NET Web API项目中,允许
https:// localhost:3000
。webapiconfig.cs
接下来,将
[enablecors]
属性添加到控制器类:您还可以跳过步骤2&为应用程序中的所有Web API控制器启用全球。
This is not a react issue. This is a security measure implemented by browsers. You need to enable cors in your asp.net web api project to allow
https://localhost:3000
.WebApiConfig.cs
Next, add the
[EnableCors]
attribute to the Controller class:You can also skip step 2 & enable it globally for all Web API controllers in your application.