Angular2 Http 不发送带有表单数据的 POST 请求

Angular2 Http not sending POST request with form data

我 post 在 Whosebug 上对这个问题进行了两次编辑,但我得到了一些不理解这个问题的人的反对票。

问题

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

所以我需要用 angular2 发送一个 post 请求来满足所有这些,所以我使用了下面的代码。

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');
  });

但是上面的代码没有起作用,表单数据被错误地解析所以服务器returns错误

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 我有解决方案,这就是为什么我要制作这个 post 以便其他人可以从中受益,我将在下面 post 它

另请注意:我正在使用第 3 方 API 并且无法在那里修改任何内容

在搜索了几个小时的文档后,我找到了 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');
  });

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

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