Angular2 Http没有发送带有表单数据

时间:2017-03-17 10:12:19

标签: angular angular2-http

我在stackoverflow上发布了两次这个问题,并且我对那些不理解问题的人进行了一些投票。

问题

Moltin api要求发送到路由https://api.molt.in/oauth/access_token的帖子请求中的正文数据仅为application/x-www-form-urlencoded,它不支持application/json,不要问我为什么会因为我不知道我知道。

所以我需要发送一个带有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,无法修改任何内容

2 个答案:

答案 0 :(得分: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');
  });

答案 1 :(得分:0)

@James,实际上您需要在WebApi项目中启用Access-Control-Allow-Origin。下面的代码要在webconfig文件下添加它。

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