簡體   English   中英

Angular 7 中的 HTTP GET 請求返回錯誤(狀態 200)

[英]HTTP GET Request in Angular 7 returning Error (status 200)

我相信我正在從 wikimedia API 獲取一個對象,但是無法弄清楚如何解析它以顯示。

//app.component.ts

import { Component } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Post } from './post';
import { Observable } from 'rxjs/Observable';

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

export class AppComponent {
  title = 'Wiki Search';
  // readonly ROOT_URL = 'https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=japan&origin=*&format=json';
  readonly ROOT_URL = 'https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=pageimages|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch=Harry Potter&origin=*&callback=JSON_CALLBACK';
  // https://en.wikipedia.org/w/api.php?action=query&format=json&gsrlimit=15&generator=search&origin=*&gsrsearch=japan"


  posts: Observable<any>;

  constructor(private http: HttpClient) {}

  getPosts(){
    this.posts = this.http.get(this.ROOT_URL)
  }
}

//app.component.html
<input type="text" placeholder="Search for pages..">
<button (click)="getPosts()">Get Posts</button>
<div *ngFor="let post of posts | async">
 {{ post | json }}
</div>

<ul class=filter-select>
  <li class="filter-select-list">
    <p class="wiki-page"></p>
  </li>
</ul>

如果我將 responseType: text 插入響應處理程序,我可以在開發控制台中將返回的數據作為錯誤讀取。

您正在調用的 URL 以 queryString 參數callback=JSON_CALLBACK

https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=pageimages|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch=Harry%20Potter&origin=*&callback=JSON_CALLBACK

這將 JSON 包裝在名為 JSON_CALLBACK 的回調方法中,該方法不是有效的 JSON,並且不允許解析。 我試過沒有那個 queryString 參數,響應現在是一個有效的純 JSON,你應該能夠解析

https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=pageimages|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch=Harry%20Potter&origin=*

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM