node 10 form data
- First, we need to import the
http
module in Node.js to handle HTTP requests and responses. This can be done using therequire
keyword:
const http = require('http');
- Next, we need to create a server using the
createServer
method from thehttp
module. This method takes a callback function as an argument, which will be triggered whenever a request is received:
const server = http.createServer((req, res) => {
// Request handling logic goes here
});
- Inside the callback function, we can access the request data using the
req
object. To handle form data, we need to use thedata
event to collect all the chunks of data and concatenate them into a single string. We can do this using theon
method of thereq
object:
let formData = '';
req.on('data', (chunk) => {
formData += chunk;
});
- Once all the form data has been received, the
end
event will be triggered. We can then parse the form data into key-value pairs using thequerystring
module:
req.on('end', () => {
const parsedFormData = querystring.parse(formData);
// Process the form data here
});
- Finally, we need to send a response back to the client using the
res
object. We can set the appropriate header and write the response body using thewriteHead
andend
methods:
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Form data received');
- To make the server start listening for incoming requests, we need to specify the port to listen on using the
listen
method:
const port = 3000;
server.listen(port, () => {
console.log(`Server running on port ${port}`);
});
Note: Make sure to replace 3000
with the desired port number.
This is the basic outline of how to handle form data in Node.js using the http
module. You can add more logic to process the form data according to your specific requirements.