2017-10-07 51 views
0

我是新來的角2,我試圖讓一個HTTP請求到Spotify的API使用以下代碼來獲取數據。

服務

import {Injectable} from '@angular/core'; 
import {Http, Headers} from '@angular/http'; 
import 'rxjs/add/operator/map'; 

@Injectable() 
export class SpotifyService{ 
    private searchUrl: string; 

    constructor(private _http:Http){ 
     // this.searchUrl = ''; 
    } 

    searchMusic(str:string, type="artist"){ 
     this.searchUrl = `https://api.spotify.com/v1/search?query=${str}&offset=0&limit=20&type=${type}&market=US`; 
     console.log(this.searchUrl); 
     return this._http.get(this.searchUrl).map(res => res.json()); 
    } 
} 

組件

import { Component } from '@angular/core'; 
import { ROUTER_DIRECTIVES } from '@angular/router'; 
import {SpotifyService} from '../../services/spotify.service'; 

@Component({ 
    moduleId: module.id, 
    selector: 'search', 
    templateUrl: 'search.component.html', 
    providers: [SpotifyService] 
}) 

export class SearchComponent { 

    searchStr:string; 

    constructor(private _spotifyService:SpotifyService){ 

    } 

    searchMusic(){ 
     //console.log(this.searchStr); 
     this._spotifyService.searchMusic(this.searchStr).subscribe(res => { console.log(res.artist.items)}); 
    } 
} 

雖然發出請求的API,我收到此錯誤

例外:響應,狀態:404找不到網址: http://localhost:3000/https/api.spotify.com/v1/search?query=a&offset=0&limit=20&type=artist&market=US

在控制檯中,的this.searchUrl值是

https://api.spotify.com/v1/search?query=a&offset=0&limit=20&type=artist&market=US

但同時使請求其在它的前面添加鹼URL即http://localhost:3000。如何從searchUrl中刪除此基礎網址,以便我可以向spotifyAPI發出請求。

+0

你能提供給我的代理。 config.json file @ kiiiinnnnnnnnnyyyy – Vignesh

回答

0

使用反向代理可以讓你的Spotify的API查詢才能正常工作。

一些背景:到那麼一個服務您的網頁是默認不允許的,大多數瀏覽器出於安全原因,其他服務器直接訪問。這包括您的Web服務器使用的主機名和端口。 developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

這可以通過使用反向代理來克服。配置將取決於用於爲頁面提供服務的Web服務器,因爲它將代表您的Web頁面進行API調用,然後將結果轉回。

如果您正在使用「NG服務」服務於你的角2應用程序,你可以配置你的代理如下:

創建您的基本項目目錄中一個新的JSON文件名爲「proxy.conf.json」

添加以下內容: { "/v1": { "target": "https://api.spotify.com", "secure": true, "changeOrigin": true, "logLevel": "debug" } }

開放的package.json並找到啓動命令。它看起來是這樣的:「開始」:「吳服」

做出如下變化:"start": "ng serve --proxy-config proxy.conf.json"

現在修改SpotifyService HTTP調用如下:

this.searchUrl = `/v1/search?query=${str}&offset=0&limit=20&type=${type}&market=US`; 
+0

我從來沒有遇到這個問題,因爲這個方法有任何特定的原因 –