如何调试“(未知URL)的HTTP故障响应:0未知错误”

时间:2018-12-08 18:06:06

标签: c# angular asp.net-core-webapi

我的API操作:

[HttpGet]
public ActionResult<IEnumerable<Loan>> Get()
{
    return _context.Loans;
}

Loan.cs

public class Loan
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string BorrowerName { get; set; }
    public decimal RepaymentAmount { get; set; }
    public decimal FundingAmount { get; set; }
}

Loan.ts

export class Loan {
    constructor(
        public Id : number,
        public BorrowerName : string,
        public RepaymentAmount : number,
        public FundingAmount : number
    ) { }
}

loans.component.ts

我可以看到http get确实在调用我的API,并且正在返回预期的数据。

import { Component, OnInit } from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import { Loan } from '../loan';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-loans',
  templateUrl: './loans.component.html',
  styleUrls: ['./loans.component.css']
})
export class LoansComponent implements OnInit {

  loans: Loan[];

  constructor(private http:HttpClient) {

    this.getLoans().subscribe((loans) => {
      this.loans = loans;
      console.log(loans);
    })
  }

  getLoans() {
    return <Observable<Loan[]>> this.http.get('http://localhost:1113/api/loans');
  }

  ngOnInit() {
  }
}

我在控制台中看到此错误:

enter image description here

我该怎么做?

1 个答案:

答案 0 :(得分:2)

控制台指出,由于CORS,请求已被阻止。您需要向服务器添加CORS支持:https://enable-cors.org/server.html

详细了解CORS:https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors