2017-02-01 35 views
2

我真的很難在Angular 2中使用POST請求。我能夠發送帶有某些參數的請求,但是我的後端(PHP Slim v3)無法獲取參數。因此,我調查了我的請求,並意識到我的angulr請求發送'content-type:application/text-plain'。因此,我的後端無法訪問變量。Angular 2發佈:未向服務器發送'content-type:application/json'

然後,我讀了很多教程,在這裏瀏覽堆棧溢出,並得出結論,我必須追加標題。

我的角類看起來是這樣的:

/** 
* Generic method for all POST-requests. 
* 
* @author 
* @date 08.01.2017 
*/ 
postData(apiUrl, data): any 
{ 

    let headers = new Headers({ 'Content-Type': 'application/json' }); 
    let options = new RequestOptions({ headers: headers }); 
    let body = JSON.stringify(data) 

    return this.http.post(apiUrl, body, options) 
     .map((responseData) => 
     { 
      if(responseData.status === 200) 
      { 
       return this.extractData(responseData); 
      } 
      else 
      { 
       this.handleRestError(null); 
      } 
     }) 
     .catch(res => { 
      return this.handleRestError(res); 
     }); 
} 

因此,所有的一切都非常簡單。但是,當我發送該請求時,奇怪的是,它以某種方式認識到,作爲OPTIONS請求並給了我'不支持的方法:OPTIONS'。

請參閱請求頭位置:

OPTIONS /auth/new HTTP/1.1 
Host: localhost:8080 
Connection: keep-alive 
Pragma: no-cache 
Cache-Control: no-cache 
Access-Control-Request-Method: POST 
Origin: http://localhost:8100 
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36 
Access-Control-Request-Headers: content-type 
Accept: */* 
Referer: http://localhost:8100/ 
Accept-Encoding: gzip, deflate, sdch, br 
Accept-Language: de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4 

從後端我的反應看起來如下:

HTTP/1.1 200 OK 
Host: localhost:8080 
Connection: close 
X-Powered-By: PHP/5.6.28 
Set-Cookie: PHPSESSID=aa546thl9maj7hamjj64vpbe95; path=/ 
Expires: Thu, 19 Nov 1981 08:52:00 GMT 
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0 
Pragma: no-cache 
Content-type: text/plain;charset=UTF-8 
Allow: POST 
Access-Control-Allow-Methods: OPTIONS 
Content-Length: 21 

而且從服務器的響應看起來是這樣的:

Allowed methods: POST 

但是,我已經設法從服務器獲得正確的響應,省略了選項參數在發佈請求中。然後,請求會正確發送,並在Chrome控制檯的請求負載中看到所需的參數。問題是我無法訪問後端的變量,因爲它一直給我一個'content-type:text/plain'。

任何想法我做錯了什麼?

感謝您的幫助!

回答

2

這是因爲你面臨CORS問題,所以你也需要允許OPTIONS方法(後端)。是這樣的:

Access-Control-Allow-Origin: * 
Access-Control-Allow-Methods: GET, POST, OPTIONS 
Access-Control-Allow-Headers: Content-Type 
Access-Control-Max-Age: 86400 

進一步瞭解CORS這裏:https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

+0

哇,感謝快速幫助!我允許GET和POST方法,但是我忘記了在POST請求中首先有一個OPTIONS請求。謝謝!! – dave0688