使用aurelia-fetch-client发布'x-www-form-urlencoded'内容

Tra*_*avo 3 aurelia aurelia-fetch-client

问题很简单:如何x-www-form-urlencoded使用Aurelia Fetch客户端发布内容?

我需要将帖子发布到使用OWIN和Katana进行身份验证的简单ASP.NET Web API服务器.

我已经尝试过的一个例子:

var loginDTO = new FormData();
loginDTO.append('grant_type', 'password');
loginDTO.append('email', 'test');
loginDTO.append('password', 'test');

return this.http
    .fetch(config.router.token, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: loginDTO
    });
Run Code Online (Sandbox Code Playgroud)

显然,这没有按预期工作.如何正确发布示例中显示的数据?

Fab*_*Luz 6

aurelia-fetch-client建立在Fetch规范之上,似乎Fetch总是发送FormDataContent-Type: multipart/form-data.

要解决此问题,您必须将参数转换为查询字符串,然后将content-type设置为x-www-form-urlenconed.您可以使用jQuery或自定义函数将对象转换为查询字符串.像这样:

//jQuery.param returns something like ?param=1&param2=2 and so on
//params = a plain javascript object that contains the parameters to be sent
this.http.fetch(url, {
  body: $.param(params),
  method: 'post',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})
.then(response => response.json())
.then(response => { 
   //your magic here
});
Run Code Online (Sandbox Code Playgroud)

我知道,这不是一个好的解决方案,但这是我到目前为止找到的最简单的方法.

  • 这种技术不再有效,因为Aurelia fetch不允许指定body +方法:'GET'+标题我不想把params放在URL中,但这确实有效.所以你可以删除正文并指定`fetch(url + params,{...})` (2认同)