我想不使用JSON而是使用x-www-form-urlencoded(URLSearchParams)将数据发送到API。
我尝试使用此代码,但API无法正确接收数据。
return fetchModule.fetch(config.apiUrl + "auth/register",
{
body: JSON.stringify({
"username": viewModel.get("username"),
"firstname": viewModel.get("firstname"),
"lastname": viewModel.get("lastname"),
"email": viewModel.get("email"),
"password": viewModel.get("password")
}),
method: "POST",
headers:{
"content-type" : "application/x-www-form-urlencoded"
}
}).then(handleErrors);
答案 0 :(得分:0)
只需将JSON.stringify
更改为URLSearchParams
并删除内容类型标头,当fetch检测到URLSearchParams作为正文时,提取将自动添加正确的内容类型
return fetchModule.fetch(config.apiUrl + "auth/register", {
body: new URLSearchParams({
"username": viewModel.get("username"),
"firstname": viewModel.get("firstname"),
"lastname": viewModel.get("lastname"),
"email": viewModel.get("email"),
"password": viewModel.get("password")
}),
method: "POST"
}).then(handleErrors);
答案 1 :(得分:0)
我认为{N}运行时无法访问URLSearchParams
类,它是特定于浏览器的。
您可以通过对象中的键的简单循环来实现相同的目的
var data = {
"username": viewModel.get("username"),
"firstname": viewModel.get("firstname"),
"lastname": viewModel.get("lastname"),
"email": viewModel.get("email"),
"password": viewModel.get("password")
};
var endocedStr = "";
for (var prop in data) {
if(endocedStr) {
endocedStr += "&";
}
endocedStr += prop + "=" + data[prop];
}
return fetchModule.fetch(config.apiUrl + "auth/register", {
body: endocedStr
method: "POST"
}).then(handleErrors);