2017-10-07 1 views
0

저는 2 번을 처음 사용하고 있으며, 다음 코드를 사용하여 데이터를 얻기 위해 Api에 http 요청을하려고합니다.

서비스 :

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을 (를) 찾을 수 없음 :콘솔에서 6,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에서이 기본 URL을 제거하면 어떻게 spotifyAPI에 요청할 수 있습니까?

+0

당신이 나에게 프록시를 제공 할 수 있습니다. config.json file @ kiiiinnnnnnnnnyyyy – Vignesh

답변

0

역방향 프록시를 사용하면 Spotify API 쿼리가 제대로 작동합니다.

일부 배경 : 보안상의 이유로 대부분의 브라우저에서는 웹 페이지를 제공하는 서버가 아닌 다른 서버에 직접 액세스 할 수 없습니다. 여기에는 웹 서버에서 사용하는 호스트 이름과 포트가 모두 포함됩니다. developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

역방향 프록시를 사용하면이 문제를 해결할 수 있습니다. 구성은 웹 페이지를 대신하여 API 호출을 수행 한 다음 결과를 다시 전달해야하므로 페이지를 제공하는 데 사용되는 웹 서버에 따라 달라집니다.

는 "NG 봉사"와 각도 2 응용 프로그램을 제공하는 경우, 다음과 같이 당신은 당신의 프록시를 구성 할 수 있습니다

는 "proxy.conf.json"

라는 이름의 기본 프로젝트 디렉토리에 새로운 JSON 파일을 만듭니다

은 다음과 같은 내용 추가 : { "/v1": { "target": "https://api.spotify.com", "secure": true, "changeOrigin": true, "logLevel": "debug" } }

열기 package.json을하고 시작 명령을 찾습니다. 그것은 다음과 같이 보일 것입니다 : "시작" "NG 역할"

는 다음과 같이 변경합니다 다음과 같이 "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

이 방법에 대한 어떤 특별한 이유와도 관련하여이 문제를 본 적이 없습니다. –