繁体   English   中英

如何将javascript json数据转换为x-www-form-urlencoded?

[英]How can I convert javascript json data to be x-www-form-urlencoded?

我需要使用以下内容类型将数据发送到服务器:

   'Content-Type': 'application/x-www-form-urlencoded'

这是我从AngularJS客户端获得的数据:

 user.loginData = {
        userName: "joe@joe.com",
        password: "smith++"
    };

有人可以通过告诉我如何转换用户名和密码来提供帮助,以便我可以将这种数据以urlencoded形式发送到服务器:

data: 'grant_type=password&username=' + username + '&password=' + password,

我找到了一个非常简单的解决方案:

encodeURIComponent(userName)

此npm模块 将对象转换为所需的对象:

var formurlencoded = require('form-urlencoded');
var obj = {
  str : 'val',
  num : 0,
  arr : [3, {prop : false}, 1, null, 6],
  obj : {prop1 : null, prop2 : ['elem']}
};

console.log(formurlencoded(obj));
// str=val&num=0&arr%5B%5D=3&arr%5B%5D%5Bprop%5D=false&arr% 
// 5B%5D=1&arr%5B%5D=null&arr%5B%5D=6&obj%5Bprop1%5D=null&o 
// bj%5Bprop2%5D%5B%5D=elem 

console.log(formurlencoded(obj, {
  ignorenull : true,
  sorted : true
}));
// arr%5B%5D=3&arr%5B%5D%5Bprop%5D=false&arr%5B%5D=1&arr%5B 
// %5D=6&num=0&obj%5Bprop2%5D%5B%5D=elem&str=val 

您可以使用以下行来设置内容类型

query: {method:'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}}

你可以在这里查看小提琴链接链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM