如果你不想使用Express来处理表单中的身体数据,你可以使用Node.js内置的http
模块来处理请求数据。以下是一个示例代码:
const http = require('http');
const querystring = require('querystring');
const server = http.createServer((req, res) => {
if (req.method === 'POST' && req.url === '/submit') {
let body = '';
req.on('data', (chunk) => {
body += chunk.toString();
});
req.on('end', () => {
const formData = querystring.parse(body);
console.log(formData);
// 做你想要的处理,比如保存数据到数据库
res.end('Form data received');
});
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(`
`);
}
});
server.listen(3000, () => {
console.log('Server is running on port 3000');
});
在以上示例中,我们创建了一个HTTP服务器,并通过req.on('data')
和req.on('end')
来处理请求体的数据。我们使用querystring.parse()
将请求体解析为一个对象,该对象包含了表单中的字段和值。你可以在req.on('end')
中进行对表单数据的处理,如保存到数据库等。