create a http server and upload a file and return a json response in javascript

Here is an example of how to create an HTTP server using Node.js that accepts file uploads and returns a JSON response:

index.tsx
const http = require('http');
const formidable = require('formidable');

const server = http.createServer((req, res) => {
  if (req.url === '/upload' && req.method.toLowerCase() === 'post') {
    const form = formidable({ multiples: false });
    
    form.parse(req, (err, fields, files) => {
      if (err) {
        res.writeHead(500, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ error: 'Internal server error' }));
      } else {
        const file = files.file;
        // Do something with the file here, e.g. save it to disk or process it
      
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ message: 'File uploaded successfully' }));
      }
    });
  } else {
    res.writeHead(404, { 'Content-Type': 'text/html' });
    res.end('Not found');
  }
});

server.listen(8080, () => {
  console.log('Server started on port 8080');
});
923 chars
29 lines

This script uses the http module to create a server that responds to HTTP requests. It also uses the formidable module to parse multipart/form-data requests, which are used for file uploads.

When a POST request is received at the /upload endpoint, the script uses formidable to extract the uploaded file from the request. You can then do something with the file (such as save it to disk or process it), and return a JSON response to the client indicating that the file was uploaded successfully.

If an error occurs during the file upload or processing, an appropriate error message is returned in the JSON response.

gistlibby LogSnag