【问题标题】:Post 'x-www-form-urlencoded' content with aurelia-fetch-client使用 aurelia-fetch-client 发布“x-www-form-urlencoded”内容
【发布时间】:2023-03-20 21:59:01
【问题描述】:

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

我需要将帖子发布到使用 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
    });

显然,这并没有按预期工作。发布示例中提供的数据的正确方法是什么?

【问题讨论】:

    标签: aurelia aurelia-fetch-client


    【解决方案1】:

    aurelia-fetch-client 是基于 Fetch 规范构建的,Fetch 似乎总是将FormData 发送为Content-Type: multipart/form-data

    要解决这个问题,您必须将参数转换为查询字符串,然后将内容类型设置为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
    });
    

    我知道,这不是一个好的解决方案,但这是迄今为止我发现的最简单的方法。

    【讨论】:

    • 此技术不再有效,因为 Aurelia fetch 不允许指定 body+method: 'GET'+headers 我不想将参数放在 URL 中,但这确实有效。所以你可以删除正文并指定fetch(url + params, {...})
    【解决方案2】:

    你会像这样使用 FormData:

    function sendForm() {
      var formData = new FormData();
      formData.append('email', 'test@test.com');
      formData.append('password', '123456');
    
      http.post(url, formData);
    }
    

    【讨论】:

      猜你喜欢
      • 2018-12-25
      • 2019-07-28
      • 1970-01-01
      • 2021-06-27
      • 2020-08-12
      • 1970-01-01
      相关资源
      最近更新 更多