I am trying to Post data in my postgres database using javascript and express. I think that the “app.use(express.json());” line in my code is the one giving me problem, but I’m new to javascript and I’m not comfortable yet with middleware.
This is the error I receive in my terminal after making the POST request with postman (it might be slightly different because i translated it from french)
error: a NULL value violates the constraint NOT NULL in the column « name » in the table « players »
This is the value of the fields i try to insert in my table:
(4, null, null, null)
This is my code
import express from 'express';
import pkg from 'pg';
const { Pool } = pkg;
const db = new Pool({
user: "postgres",
host: "localhost",
database: "postgres",
password: "123456",
port: 5433
});
const app = express();
const port = process.env.PORT || 3000;
app.use(express.json());
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.post('/players', async (req, res) => {
console.log(req.body);
const {
name,
email,
password,
} = req.body;
try{
const client = await db.connect();
const result = await client.query(
'INSERT INTO players (name,email,password) VALUES ($1, $2, $3) RETURNING *',
[name,email,password]);
res.status(201).json(result.rows[0]);
client.release();
} catch(err){
console.error(err);
res.status(500).send('Error creating user');
}
});
app.listen(port, () => {
console.log(`Server listening on port ${port}`)
});
I was expecting the value to be the same as the body of my POST request :
{
"name": "Zelda",
"email": "[email protected]",
"password": "zelda123",
}
The server is working because if I make the get request, I get back “Hello world”