Having trouble with a project for school. I'm trying to make a POST request, to insert a new user into a table via Insominia. I keep getting a null value error of username. I've sent my code to one of the TA's and they are not receiving this error. The code was working fine for them. So we couldn't figure out the problem on my end. I'm wondering if it has to do with Insomina. Any help would be greatly appreciated thank you.
Error Message:
{
"error": {
"message": "null value in column \"username\" of relation \"users\" violates not-null constraint",
"status": 500
}
}
My request via Insomina:
{
"username": "newUser",
"password": "password"
}
index.js
app.use(express.json());
ORM for User class, the createNewUser function is for POST request.
user.js
/* Create a new user function for post request. Inserting user name and password.
Returning the id, username, and password. */
static async createNewUser(username, password) {
const results = await db.query(
`INSERT INTO users (username, password)
VALUES ($1, $2)
RETURNING id, username, password`,
[username, password]);
console.log(results.rows);
let { id } = results.row[0];
return new User(id, username, password);
}
The POST route is giving me trouble, req.body returning undefined.
userRoutes.js
/* Create a new user by requesting the body of username and password
and returning the json.*/
router.post('/', async function (req, res, next) {
try {
console.log(req.headers);
let id = await User.createNewUser(req.body.username, req.body.password);
console.log(id);
return res.json(id);
} catch (e) {
return next(e);
}
});
Header logs in terminal. Im wondering if my problem lies here because I'm not getting Content-Type: application/json.
{
host: 'localhost:3001',
'user-agent': 'insomnia/2021.4.1',
authorization: 'Basic Og==',
accept: '*/*',
'content-length': '51'
}
headers in Insomina
X-Powered-By: Express
Access-Control-Allow-Origin: *
Content-Type: application/json; charset=utf-8
Content-Length: 121
ETag: W/"79-wzArjA/Y97Lx74leuLv1MyJkXDQ"
Date: Mon, 06 Sep 2021 16:49:00 GMT
Connection: keep-alive
Keep-Alive: timeout=5
The answer is likely due to a missing Content-Type
header. The "headers in Insomnia" are the response headers that your application is sending back.
In Insomnia, make sure that you have JSON selected as the Body
type:
You'll also see the Content-Type
set in the Header
tab once this is selected:
Once that header is set, your request should complete successfully