问题很简单:如何使用 Aurelia Fetch 客户端发布 x-www-form-urlencoded 内容?
The question is simple: how do I post x-www-form-urlencoded content with Aurelia Fetch client?
我需要将帖子发送到使用 OWIN 和 Katana 进行身份验证的简单 ASP.NET Web API 服务器.
I need to make the post to a simple ASP.NET Web API server that is using OWIN and Katana for authentication.
我已经尝试过的示例:
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 });显然,这没有按预期工作.发布示例中显示的数据的正确方法是什么?
Obviously, that didn't work as intended. How is the correct way to go about posting the data presented in the example?
推荐答案aurelia-fetch-client 是建立在 Fetch 规范之上的,看起来 Fetch 总是发送 FormData 作为 Content-类型:multipart/form-data.
The aurelia-fetch-client is built on Fetch specification, and it seems that Fetch always sends FormData as Content-Type: multipart/form-data.
要解决这个问题,您必须将参数转换为查询字符串,然后将内容类型设置为 x-www-form-urlenconed.您可以使用 jQuery 或自定义函数将对象转换为查询字符串.像这样:
To get around this, you have to convert the parameters to a query string and then set the content-type to x-www-form-urlenconed. You can use jQuery or a custom function to convert the object to a query string. Like this:
//jQuery.param returns something like ?param=1¶m2=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 });我知道这不是一个好的解决方案,但这是我目前找到的最简单的方法.
Not a good solution, I know, but that's the easiest way I found so far.
更多推荐
使用 aurelia
发布评论