【问题标题】:Angular 2 lost data from http.get requestAngular 2从http.get请求丢失数据
【发布时间】:2017-08-09 12:17:11
【问题描述】:

我对 http.get 请求有疑问。 请求后数据显示1秒,然后消失。 组件.ts:

http.get('http://localhost:52875/api/clients/1').subscribe(result => {
        this.client = result.json();
    });

http.get('http://localhost:52875/api/client_balances/1').subscribe(result => {
        this.cash = result.text();
    });

component.html:

<p *ngIf="!client"><em>Loading...</em></p>
<form *ngIf="client">
        {{client.first_name}}
        {{client.last_name}}
<br />
        {{cash}}
<br />
<a class="alert-link" [routerLink]="['/cash/add']">Add</a>
<a class="alert-link" [routerLink]="['/cash/out']">Out</a>
</form>

【问题讨论】:

  • 浏览器是否出现异常?
  • 代码本身似乎是正确的
  • broser中没有异常
  • 我发现了错误:“XMLHttpRequest 无法加载 localhost:52875/api/products。请求的资源上没有 'Access-Control-Allow-Origin' 标头。因此不允许使用 Origin 'localhost:50749'访问。”
  • 您的 Web 应用程序是否托管在 localhost:50749 上?如果是这样,那么您正在处理 CORS 问题:en.wikipedia.org/wiki/Cross-origin_resource_sharing。要解决它,您基本上需要允许您的api 接受来自其他来源的请求

标签: angular http get


【解决方案1】:

问题是我没有授予对 API 的访问权限。我正在使用 ASP.NET Core。我刚刚在 Startup.cs 中打开了对我的 WEB 应用程序的访问权限:

public void ConfigureServices(IServiceCollection services)
    {
        // Added this:
        services.AddCors(options =>
        {
            options.AddPolicy("AllowSpecificOrigin",
                builder => builder.WithOrigins("http://localhost:50749"));
        });
        //
        Other code
        //
        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
    ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();
        // Added this:
        app.UseCors("AllowSpecificOrigin");

        app.UseMvc();
    }

【讨论】:

    猜你喜欢
    • 2017-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-01
    • 1970-01-01
    • 2014-03-03
    • 1970-01-01
    • 2020-08-29
    相关资源
    最近更新 更多