2017-03-17 126 views
1

我在stackoverflow上發佈了兩次這個問題,我得到了一些不理解問題的人的投票。Angular2 Http不發送帶有表單數據的POST請求

的問題

Moltin API要求在POST請求體發送數據來作爲application/x-www-form-urlencoded而已,它不支持application/json路線https://api.molt.in/oauth/access_token,不要問我爲什麼,因爲我不知道。

因此,我需要發送一個滿足所有這一切的angular2的發佈請求,所以我使用了下面的代碼。

let headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded'}); 
let options = new RequestOptions({headers}); 

let body = { 
    client_id: env.MOLTIN_CLIENT_ID, 
    grant_type: 'implicit' 
} 

this.http.post('https://api.molt.in/oauth/access_token', body, options) 
    .subscribe((result) => { 
    console.log(result, 'result reached') 
    }, (err) => { 
    console.log(err, 'error reached'); 
    }); 

但上面的代碼永遠不會奏效,因爲瀏覽器發送預檢期間FORMDATA被錯誤地分析,這樣服務器返回錯誤

XMLHttpRequest cannot load https://api.molt.in/oauth/access_token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 400.

之所以拋出這個錯誤,是服務器不承認的OPTIONS請求。

我也嘗試使用JSON.stringify(body)將字體值進行字符串化,但這並沒有幫助。

PS我有解決方案,這就是爲什麼我提出這個職位,以便其他人可以從中受益,我將它張貼不久下面

還要注意:我使用第三方API,不能修改那裏的任何內容

回答

3

在搜索了幾個小時的文檔後,我發現URLSearchParams並決定嘗試一下,看它是否奏效。

下面是最終的解決方案

let headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded'}); 
let options = new RequestOptions({headers}); 
let body = new URLSearchParams(); 
body.append('client_id', env.MOLTIN_CLIENT_ID); 
body.append('grant_type', 'implicit'); 

this.http.post('https://api.molt.in/oauth/access_token', body.toString(), options) 
    .subscribe((result) => { 
    console.log(result, 'result reached') 
    }, (err) => { 
    console.log(err, 'error reached'); 
    }); 
0

@詹姆斯,其實你需要啓用訪問控制允許來源在你的WebAPI項目。下面的代碼你想添加它在webconfig文件下。

<configuration> 
    <system.webServer> 
    <httpProtocol> 
    <customHeaders> 
     <add name="Access-Control-Allow-Origin" value="*" /> 
    </customHeaders> 
    </httpProtocol> 
</system.webServer> 
</configuration> 
+0

如果你讀了問題提得好,我使用的是第三方API,我沒有接觸它,並且無法修改API –

+0

你需要與身體一起傳遞頭。所以試試這個this.http.post('https://api.molt.in/oauth/access_token',{headers,body},options) –