Angular 7中的HTTP GET请求返回错误(状态200)

时间:2019-03-26 23:42:48

标签: javascript angular get angular7

我相信我是从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:文本,则可以将返回的数据作为开发控制台中的错误读取。

1 个答案:

答案 0 :(得分:1)

您正在调用的URL以queryString参数i

结尾
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=*&callback=JSON_CALLBACK