nodejs querystring踩坑笔记----只能用于表单提交

时间:2023-03-09 00:59:11
nodejs querystring踩坑笔记----只能用于表单提交

API中的实例:

var http = require('http');
var querystring = require('querystring');
var postData = querystring.stringify({
'msg' : 'Hello World!'
}); var options = {
hostname: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
}; var req = http.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
res.on('end', () => {
console.log('No more data in response.')
})
}); req.on('error', (e) => {
console.log(`problem with request: ${e.message}`);
}); // write data to request body
req.write(postData);
req.end();

刚开始不理解querystring是干什么的,本想这里不用JSON.stringify()应该是Node特有的方法吧,也没打印出来看。

当我将一个obj对象(含多层)POST发送给服务器时,一直不对。

这里已经改为:

'Content-Type': 'application/json'

还是不对。

最后

var querystring = require('querystring');

var postData = querystring.stringify({
name:'abc',
age: 12,
array:[{name:'234'},{name:'987'}]
}) console.log(postData);

nodejs querystring踩坑笔记----只能用于表单提交

明显:对于多级obj经由querystring处理之后就不对了。

很快就明白了,原来querystring是将对象转为表单格式的字符串,so querystring只能用于application/x-www-form-urlencoded的情况。

form请求是没办法处理层级问题的。

对于application/json还是用JSON.stringify()吧。

对于node请求建议还是使用npm第三方封装的请求工具 如:request 或者javascript原生的fetch