iT邦幫忙

0

Angular的CORS問題

今天使用外部API碰到CORS的問題,
但是如果使用jquery請求的話就不會有問題,
請問我Angular的http請求是哪邊出錯了呢?

API位址

const url = 'https://geoapi.heartrails.com/api/json?method=suggest&matching=like&keyword=' + this.keyword + '&jsonp=?';

jquery版

    $.getJSON(
      url,
      null,
      data => {
        console.log(data);
      }
    );

Angular的http版

    this.http.get(url).map((response: Response) => response.json()).subscribe(
      data => {
        console.log(data);
      }
    );
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

3
暐翰
iT邦大師 1 級 ‧ 2018-04-05 18:46:06
最佳解答



添加jsnop_provider
接著把你的http物件類別Http換成Jsnop

參考:【 How to make a simple JSONP asynchronous request in Angular 2?
】https://goo.gl/5QY8oT

twrichgod iT邦新手 5 級 ‧ 2018-04-05 20:32:28 檢舉

感謝回答,明天上班就試試看。

twrichgod iT邦新手 5 級 ‧ 2018-04-06 09:41:09 檢舉

感謝,成功了!
不過可能是Angular版本的關係,
命令有點不同。

xx.module.ts:

import { JsonpModule } from '@angular/http';
imports: [JsonpModule]

component:

import { Jsonp } from '@angular/http';

API的url要加JSONP_CALLBACK,變成:

const url = 'https://geoapi.heartrails.com/api/json?method=suggest&matching=like&keyword=' + this.keyword + '&jsonp=JSONP_CALLBACK';
暐翰 iT邦大師 1 級 ‧ 2018-04-06 11:41:24 檢舉

/images/emoticon/emoticon12.gif /images/emoticon/emoticon12.gif

我要發表回答

立即登入回答