2017-10-07 73 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

我从来没有遇到这个问题,因为这个方法有任何特定的原因 –