在 hapi 中访问 FormData
Accessing FormData in hapi
所以我使用 XMLHttpRequest 从 chrome-extension 向我的 hapi api 发布一些数据:
var xhr =new XMLHttpRequest();
xhr.open('POST', 'http://my-url.com/signup', true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
let params = {} ;
params.username = "username";
params.password = "password";
xhr.send(JSON.stringify(params));
xhr.onreadystatechange = function(response){...}
似乎工作正常(通过分析 chromes 调试器中的网络选项卡)
现在,在服务器端,来自 Express,我原以为这些数据会在 req.params
中可用,但一些研究让我相信这应该有效:
module.exports = [{
method:'POST',
path: '/signup',
config:{
payload:{
output:'data',
parse:true,
},
handler:function(request, reply){
console.log( `signing up user: ${request.payload.username}` );
.....
}
}
}
但是这会打印
signing up user: undefined
并将其切换为打印字符串化的 request.payload
输出:
signing up user: {"{\"username\":\"apa\",\"password\":\"apa\"}":""}
hapi 中是否有内置功能来解析它,或者我是否需要 "roll my own"?
FormData 会将您的有效载荷格式化为 multipart/form-data
有效载荷。但是您设置的 Content-type header of application/x-www-form-urlencoded
。它们是完全不同的编码。所以你混淆了 hapi 的有效负载解析器关于它接收的有效负载编码。
删除行:
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
那应该可以了。
所以我使用 XMLHttpRequest 从 chrome-extension 向我的 hapi api 发布一些数据:
var xhr =new XMLHttpRequest();
xhr.open('POST', 'http://my-url.com/signup', true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
let params = {} ;
params.username = "username";
params.password = "password";
xhr.send(JSON.stringify(params));
xhr.onreadystatechange = function(response){...}
似乎工作正常(通过分析 chromes 调试器中的网络选项卡)
现在,在服务器端,来自 Express,我原以为这些数据会在 req.params
中可用,但一些研究让我相信这应该有效:
module.exports = [{
method:'POST',
path: '/signup',
config:{
payload:{
output:'data',
parse:true,
},
handler:function(request, reply){
console.log( `signing up user: ${request.payload.username}` );
.....
}
}
}
但是这会打印
signing up user: undefined
并将其切换为打印字符串化的 request.payload
输出:
signing up user: {"{\"username\":\"apa\",\"password\":\"apa\"}":""}
hapi 中是否有内置功能来解析它,或者我是否需要 "roll my own"?
FormData 会将您的有效载荷格式化为 multipart/form-data
有效载荷。但是您设置的 Content-type header of application/x-www-form-urlencoded
。它们是完全不同的编码。所以你混淆了 hapi 的有效负载解析器关于它接收的有效负载编码。
删除行:
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
那应该可以了。