(未知网址)的Http失败响应:0 Angular 5上的未知错误

时间:2017-12-13 03:38:37

标签: javascript angular typescript

在angular 5服务中从http://samples.openweathermap.org/data/2.5/history/city?q=Warren,OH&appid=b6907d289e10d714a6e88b30761fae22检索数据时出现以下错误。

message: "Http failure response for (unknown url): 0 Unknown Error"
name: "HttpErrorResponse"
ok: false
status: 0
statusText: "Unknown Error"

在浏览器上直接输入api URL时,它将返回JSON对象列表。 以下是我的服务代码 weather.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http'
import 'rxjs/add/operator/map';

@Injectable()
export class WeatherService {

  constructor(private _http: HttpClient) { }

  dailyForecast() {
    return this._http.get("http://samples.openweathermap.org/data/2.5/history/city?q=Warren,OH&appid=b6907d289e10d714a6e88b30761fae22")
    .map(result => result);
  }
}

app.module.ts

上的代码
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { WeatherService } from './weather.service';

import { AppComponent } from './app.component';


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [WeatherService],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts

上的代码
import { Component } from '@angular/core';
import { WeatherService } from './weather.service';
import { Chart } from 'chart.js';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  constructor(private _weather: WeatherService) {}

  ngOnInit() {
    this._weather.dailyForecast()
    .subscribe(res => {
      console.log(res)
    })
  }
}

我无法弄清楚它上面出了什么问题。

2 个答案:

答案 0 :(得分:1)

这是HttpClient上的错误,您无法修复否则使用: 始终使用JSON.parse进行前缀剥离。

答案 1 :(得分:0)

这是CORS问题,请在后端代码中添加header("Access-Control-Allow-Origin: *");