2017-11-14 10 views
1

角度2のクライアント(asp.netコア2.0 APIサーバー)でhttp POSTリクエストを実行しようとしています。http http GETが動作している間、Angular 2クライアントのPOSTは動作しません。

最初に415 error (Unsupported Media)がありました。

ヘッダーを追加すると、エラーresponse to preflight request doesn't pass access control check: No 'Access-Control-Origin' header is present on the requested resourceが発生します。

同じサービスのHttpは完璧に(ヘッダーなしで)動作しています。

import {Injectable} from '@angular/core'; 
 
import {Http, Headers} from '@angular/http'; 
 

 
export class MyService { 
 

 
    constructor(private http: Http) {} 
 
    
 
    // This is working 
 
    getStudents(): Observable <string[]>{ 
 
     return this.http.get('https://localhost:44753/api/students', {withCredentials:true}) 
 
     .map((res:Response)=> res.Json()); 
 
    } 
 
    
 
    // Return 415 
 
    getStudent(name): Observable <string[]>{ 
 
    let data = { 
 
     "name": name 
 
    } 
 
     return this.http.get('https://localhost:44753/api/students', JSON.Stringify(data),   {withCredentials:true}) 
 
     .map((res:Response)=> res.Json()); 
 
    } 
 
    
 
    // Return 401 
 
    getStudent2(name): Observable <string[]>{ 
 
     let data = { 
 
     "name": name 
 
     } 
 
    
 
     let headers = new Header(); 
 
     headers.append('Content-Type', 'application/json); 
 
     headers.append('Access-Control-Allow-Origin', '*'); 
 

 
     let options = new RequestOptions({ headers:headers , withCredentials:true }); 
 

 
     return this.http.get('https://localhost:44753/api/students', JSON.Stringify(data),   options) 
 
      .map((res:Response)=> res.Json()); 
 
    } 
 
    
 
}

誰かが私がこれを解決するのに役立つことはできますか?

+0

どのサーバーを使用していますか? Angular開発サーバーまたは何らかのプロダクションサーバーを使用していますか? Angular 2を使用している場合は、新しいバージョン(5)にアップグレードして動作するか確認してください。 –

答えて

0

CORS要求のためにサーバを設定する必要があるようです。

0

あなたは、あなたの代わりに文字列[]

の単一の文字列を期待している場合はget呼び出し

public getStudent = (name: string): Observable<string[]> => { 

    let params: URLSearchParams = new URLSearchParams(); 
    params.set('name', name); 
    this.options.params = params; 

    return this.http.get('https://localhost:44753/api/students', this.options) 
     .map(
     data => data.json() 
     ); 
}; 

もダブルチェックに代わり、ヘッダーのSearchParamsを使用し、[HTTPGET(「{名前}」で飾ることができます)]あなたのWebApiメソッド

[HttpGet("{name}")] 
public List<string> Students (string name){..... 
関連する問題