I am trying to insert data into the SQL Server database using NodeJS.
When I ran the service and opened the browser-> localhost:5000 and I
got the page:
Error: Cannot Get (404) in NodeJS.
Seeking help if I am missing something. The database table has only 2 columns
Here's my code. Hoping for some assistance, will be highly appreciated
const express = require('express');
const sql = require('mssql');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(express.json());
const config = {
user: 'sa',
password: 'password',
server: 'ServerName\\MSSQL2019EX',
database: 'Contacts',
options: {
encrypt: false,
trustServerCertificate: false
}
};
app.post('/', async (req, res) => {
try {
await sql.connect(config);
const pool = new sql.ConnectionPool(config);
await pool.connect();
const transaction = new sql.Transaction(pool);
await transaction.begin();
try {
for (const user of req.body) {
await new sql.Request(transaction)
.input('name', sql.NVarChar, user.name)
.input('email', sql.NVarChar, user.email)
.query(`
INSERT INTO Users (Name, Email)
VALUES (@name, @email)
`);
}
await transaction.commit();
res.sendStatus(200);
} catch (err) {
await transaction.rollback();
throw err;
}
} catch (error) {
console.error('SQL error:', error);
res.status(500).send('Database error');
}
});
app.listen(5000, () => {
console.log('Server running on port 5000');
});
Asking for suggestion of fixing the script.
app.postcode), and can handle that. There's nothing in what you've shown us which will handle GET requests. But if you simply visithttp://localhost:5000in your browser, your browser will always send a GET request to the app server. I think nodeJS is telling you it doesn't have a route which can handle your GET request, which the content of your code seems to agree with. Perhaps you would be better to test your endpoint with a tool such as PostMan instead, ensuring you set it to send a POST and supply parameters