Complete the code to import the SQL library in an Express app.
const sql = require('[1]');
The mysql package is used to connect SQL databases with Express apps.
Complete the code to create a connection to the SQL database.
const connection = sql.createConnection({ host: 'localhost', user: 'root', password: '[1]', database: 'testdb' });The password field should be the actual password string for the database user.
Fix the error in the query execution code by completing the blank.
connection.query('SELECT * FROM users', function(err, results) { if (err) throw [1]; console.log(results); });
The error object passed to the callback is named err, so we throw err to handle errors properly.
Fill both blanks to create a simple Express route that queries the database and sends results.
app.get('/users', (req, res) => { connection.query('[1]', (err, results) => { if (err) return res.status(500).send(err); res.[2](results); }); });
res.send() which sends raw data, not JSON.The SQL query should select all users. The response should send JSON data to the client.
Fill all three blanks to handle a POST request that inserts a new user into the database.
app.post('/add-user', (req, res) => { const { name, email } = req.body; const query = 'INSERT INTO users (name, email) VALUES (?, ?)'; connection.query(query, [[1], [2]], (err, results) => { if (err) return res.status(500).send(err); res.[3]({ message: 'User added', id: results.insertId }); }); });
res.send instead of res.json.We pass name and email from the request body as parameters to the query. Then respond with JSON to confirm success.