2017-06-15 234 views
0
import { Injectable } from '@angular/core'; 
import { Http } from '@angular/http'; 
import 'rxjs/add/operator/map'; 

import { Event, SearchParameters } from './event.model'; 

@Injectable() 
export class EventService {  
    private _url = "http://localhost:36888/api/HealthFairEvents"; 

    constructor(private _http: Http) { 

    } 

    getEvents(SearchParameters) {   
     return this._http.post(this._url + "/HealthFairEventSL", SearchParameters).map(res => res.json()); 
    } 

    getEvent(id: number) {   
     return this._http.get(this._url + "/GetHealthFairEvent/" + id).map(res => res.json()); 
    } 

    addEvent(event: any){ 
     console.log('add'); 
     console.log(JSON.stringify(event)); 
     return this._http.post(this._url + "/PostHealthFairEvent", JSON.stringify(event)).map(res => res.json()); 
    } 

    updateEvent(event: Event){ 
     console.log('update');   
     console.log(JSON.stringify(event)); 
     return this._http.put(this._url + "/PutHealthFairEvent/" + event.HealthFairEventId, JSON.stringify(event), 

     ).map(res => res.json()); 
    } 
} 

它看起來像我需要發送'Access-Control-Allow-Origin:*'或CORS與_http請求。但我無法做到。我檢查了Angular4文檔,但沒有成功。請幫助我謝謝。415 - 不支持的媒體類型

+0

這是一個後端問題。你在使用.NET嗎? –

+0

是的。我正在使用基於.Net的Web API。在WEB API端啓用CORS?我的問題是如何從角度發送來自HTTP對象的允許來源。 –

回答

0

CORS發生在服務器端,客戶端上唯一需要的頭是內容類型。

例子:

import { Http, Response, Headers, RequestOptions } from '@angular/http'; 

getEvent(id: number) { 
     let headers = new Headers({ 'Content-Type': 'application/json' }); 
     let options = new RequestOptions({ headers: headers }); 
     return this._http.get(this._url + "/GetHealthFairEvent/" + id, options).map(res => res.json()); 
    } 

在服務器端,要啓用CORS有幾種方法可以做到這一點。最簡單的是從後約微軟CORSinstalling the Microsoft.AspNet.WebApi.Cors package from NuGet.

<system.webServer> 
    <httpProtocol> 
    <customHeaders> 
     <add name="Access-Control-Allow-Origin" value="http://localhost:4200" /> 
     <add name="Access-Control-Allow-Methods" value="*" /> 
     <add name="Access-Control-Allow-Credentials" value="true" /> 
    </customHeaders> 
    </httpProtocol> 
</system.webServer> 

更詳細的信息,這對添加到您的web.config https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api

0

正確的答案是,

updateEvent(event: HealthFairEvent){ 
     console.log('update');   
     console.log(JSON.stringify(event)); 
     let customHeader = new Headers(); 
        customHeader.append('Access-Control-Allow-Origin', '*'); 

     return this._http.put(this._url + "/XX/" + event.HealthFairEventId, event, { headers: customHeader }).map(res => res.json());   
    } 
相關問題