我在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,不能修改那里的任何内容
如果你读了问题提得好,我使用的是第三方API,我没有接触它,并且无法修改API –
你需要与身体一起传递头。所以试试这个this.http.post('https://api.molt.in/oauth/access_token',{headers,body},options) –