簡體   English   中英

Angular 2 Post:不向服務器發送“內容類型:應用程序/json”

[英]Angular 2 Post: Not sending 'content-type: application/json' to server

我真的很努力處理 Angular 2 中的 POST 請求。我可以發送帶有某些參數的請求,但是我的后端 (PHP Slim v3) 無法獲取這些參數。 因此,我調查了我的請求,並意識到我的 Angular 請求發送了“內容類型:應用程序/文本純文本”。 因此我的后端無法訪問這些變量。

然后,我閱讀了很多教程,瀏覽了堆棧溢出,得出的結論是我必須附加標題。

我的角度類看起來像這樣:

/**
* 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

但是,我設法通過省略 post 請求中的options參數從服務器獲得了正確的響應。 然后請求被正確發送,我在 Chrome 控制台的請求負載中看到了所需的參數。 問題是我無法訪問后端的變量,因為它一直給我一個“內容類型:文本/純文本”。

知道我做錯了什么嗎?

提前感謝您的幫助!

這是因為您面臨 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM