简体   繁体   English

尝试从反应应用程序的本地主机 web api 端点获取数据 - NoCors 错误

[英]Trying to Fetch data from a localhost web api end point from react app - NoCors error

I have created an end point in csharp web api which returns some json data, it works fine on postman.我在 csharp web api 创建了一个端点,它返回一些 json 数据,它在 Z03D476861AFDFA8814Z1 上工作正常。 but when I try the same url on my react app I get the following error但是当我在我的反应应用程序上尝试相同的 url 时,我收到以下错误

React code反应代码

fetch('https://localhost:44391/agency')
  .then(response => response.json())
  .then(json => console.log(json))

Error错误

Access to fetch at 'https://localhost:44391/agency' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I followed this link Trying to use fetch and pass in mode: no-cors and tried the following code我关注了这个链接Trying to use fetch and pass in mode: no-cors并尝试了以下代码

fetchData () {
           var proxyUrl = 'https://cors-anywhere.herokuapp.com/',
    targetUrl = 'https://localhost:44391/agency'
fetch(proxyUrl + targetUrl)
        .then(blob => blob.json())
        .then(data => {
            console.log(data);
            return data;
        })
        .catch(e => {
            console.log(e);
            return e;
        });
      }

I get this error我收到这个错误

GET https://cors-anywhere.herokuapp.com/https://localhost:44391/agency 404 (Not Found)
SyntaxError: Unexpected token N in JSON at position 0

Note The steps from the link which I could not do was注意我无法执行的链接中的步骤是

git clone https://github.com/Rob--W/cors-anywhere.git - DONE git 克隆https://github.com/Rob--W/cors-anywhere.git - 完成

cd cors-anywhere/ - DONE cd cors-anywhere/ - 完成

npm install - DONE npm 安装 - 完成

heroku create - COULD NOT DO THIS. heroku 创建 - 不能这样做 DO I NEED HEROKU, I AM NOT SURE WHY我需要 HEROKU,我不知道为什么

git push heroku master - NOT DONE YET git 推 heroku 主 - 尚未完成

Your help is much appreciated非常感谢您的帮助

Thanks P谢谢P

Update更新

I have enabled CORS on my c# web api following the link https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#dp I have enabled CORS on my c# web api following the link https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#dp

section i followed was CORS with default policy and middleware我遵循的部分是CORS with default policy and middleware

and my code is bellow我的代码如下

I have tried options.AddPolicy and options.AddDefaultPolicy but when I call from react app it still does not work我已经尝试过options.AddPolicyoptions.AddDefaultPolicy但是当我从反应应用程序调用时它仍然不起作用

namespace React_NalONE_API
{
    public class Startup
    {
        readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                // options.AddPolicy(name: MyAllowSpecificOrigins,
                //                 builder =>
                //               {
                //                 builder.WithOrigins("http://localhost/*",
                //                                   "https://localhost/*");
                //         });

                options.AddDefaultPolicy(
                builder =>
                {
                    builder.WithOrigins("http://localhost/*",
                                        "https://localhost/*");
                });
            });
            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseCors();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers().RequireCors(MyAllowSpecificOrigins);
            });
        }
    }
}

You don't need Heroku if you're just trying to test it locally.如果您只是想在本地进行测试,则不需要 Heroku。 I'm assuming that bit on the tutorial you used was just to deploy the application, in order to demonstrate it's functionality.我假设您使用的教程中的那一点只是为了部署应用程序,以展示它的功能。 You don't necessarily need to follow through with that bit to get everything to work.您不一定需要遵循这一点来让一切正常工作。

The issue seems to be with CORS permissions, usually browsers don't let you make CORS requests unless the response from the origin that you're requesting contains the right CORS headers.问题似乎与 CORS 权限有关,通常浏览器不允许您发出 CORS 请求,除非来自您请求的源的响应包含正确的 CORS 标头。 I would check this out for some more context.我会检查一下以获取更多上下文。

If enabling CORS is something you're looking to do, then you probably want to enable CORS in .NET (I'm assuming that you're using .NET - whatever framework you're using, there should be a way to enable CORS) If enabling CORS is something you're looking to do, then you probably want to enable CORS in .NET (I'm assuming that you're using .NET - whatever framework you're using, there should be a way to enable CORS)

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

相关问题 如何从对象数组中获取数据,并通过 API 端点将其传递到 .fetch() 使用 React 所需的对象值? - How can I fetch data from an array of objects, pass it through an API end point to .fetch() the needed object value using React? 如何从通过 Fetch API 发送的后端 (localhost) 获取数据? (PHP、Fetch、React Native、POST 请求) - How do I fetch data from my back-end (localhost) that's being sent through Fetch API? (PHP, Fetch, React Native, POST request) 我正在尝试从Rest API中获取json数据以进行反应,但是它显示了一些错误 - I am trying to fetch json data from Rest API into react, but it showing some error 在反应中从 Api 获取数据 - Fetch data from Api in react 从 React 应用程序中的 api 获取数据之前的页面渲染导致错误 - Page rendering before the data fetch from api in React app is causing error 尝试使用javascript从api获取数据 - Trying to fetch data from an api using javascript 尝试使用 fetch 从 API 获取数据 - Trying to get data from an API using fetch 尝试从Windows 8应用中的服务器获取数据 - Trying to fetch data from server in windows 8 app 在反应客户端从本地主机 cassandra db 获取数据 - Fetch data from localhost cassandra db in react clientside 从Web API使用Vue提取数据 - Fetch data with Vue from Web API
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM