gpt4 book ai didi

javascript - 如何获取Node.JS字段值(提交的表单数据)

转载 作者:行者123 更新时间:2023-12-03 01:32:31 25 4
gpt4 key购买 nike

我使用没有框架(without-express)的 Node.js。

我当前的代码。

const { headers, method, url } = req;
let body = [];
req.on('error', (err) => {
console.error(err);
}).on('data', (chunk) => {
body.push(chunk);
}).on('end', () => {
console.log(body)
body = Buffer.concat(body).toString();

console.log(body)
res.writeHead(200, {'Content-Type': 'text/html\; charset=utf-8'});
res.write(body)
res.end()
});

回应

------WebKitFormBoundaryAExpj6oapW6tzLe8
Content-Disposition: form-data; name="field-one"

Test value of field one
------WebKitFormBoundaryAExpj6oapW6tzLe8
Content-Disposition: form-data; name="field-two"

Test value of field-two
------WebKitFormBoundaryAExpj6oapW6tzLe8--

在此测试示例中,字段一的值为字段一的测试值,字段二的值为字段二的测试值 如何获取该字段按字段名称排列?

NPM 模块是可以接受的。

最佳答案

NPM module are acceptable

您可以使用parse-formdata包。

const parseFormdata = require('parse-formdata')
const http = require('http')

http.createServer((req, res) => {
parseFormdata(req, (err, data) => {
if (err) {
// Set whatever status code you want
return res.end('Error...');
}
console.log('fields:', data.fields)
data.parts.forEach(function(part) {
console.log('part:', part.fieldname)
});

res.writeHead(200, {
'Content-Type': 'text/html\; charset=utf-8'
});

res.end();
});

}).listen(8080)

如果您想学习自己解析表单数据,可以阅读该包的代码。

关于javascript - 如何获取Node.JS字段值(提交的表单数据),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51224383/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com