filter out json from http get and post to database in typescript

Assuming you are using Node.js with TypeScript, you can use the http module to receive HTTP requests and parse the JSON data from the request body. Then you can use a database driver like mysql to insert the data into the database.

Here's an example of how to filter out JSON from HTTP requests and insert it into a MySQL database:

index.ts
import * as http from 'http';
import * as mysql from 'mysql';

const server = http.createServer((req, res) => {
  if (req.method === 'POST' && req.url === '/data') {
    let body = '';
    req.on('data', (chunk) => {
      body += chunk.toString();
    });
    req.on('end', () => {
      const data = JSON.parse(body); // parse JSON data from request body
      const db = mysql.createConnection({
        host: 'localhost',
        user: 'username',
        password: 'password',
        database: 'dbname'
      });
      db.connect((err) => {
        if (err) throw err;
        const sql = 'INSERT INTO data (field1, field2, field3) VALUES (?, ?, ?)';
        db.query(sql, [data.field1, data.field2, data.field3], (err) => {
          if (err) throw err;
          res.writeHead(200, {'Content-Type': 'text/plain'});
          res.end('Data inserted successfully');
        });
      });
    });
  } else {
    res.writeHead(404, {'Content-Type': 'text/plain'});
    res.end('Not found');
  }
});

server.listen(8000, () => {
  console.log('Server started on port 8000');
});
1082 chars
37 lines

In this example, we create an HTTP server and listen for POST requests to the /data endpoint. We extract the JSON data from the request body, create a MySQL connection, and insert the data into the data table using a parameterized query. Finally, we send a response back to the client with a success message.

Note that this example uses callbacks for simplicity, but you should consider using promises or async/await for better error handling and code readability.

gistlibby LogSnag