Answer the question
In order to leave comments, you need to log in
How to fix wrong get user method in sqlite in node js app?
I write Rest API on Node.js + Express.js
Sqlite database.
There is a method that gets one user by id. If I enter the user id in the request, which is in the database, then I can normally get it without any errors with status 200.
If I enter the wrong id, which is not in the database, then I do not get the user, but the status code is still 200 , errors are not handled for some reason
How can I fix the method to work correctly?
Valid id:
Incorrect id:
users.js:
const express = require('express')
const db = require("../database");
const router = express.Router()
//get single user
router.get("/api/user/:id", (req, res, next) => {
let userId = [req.params.id];
db.get(`SELECT * FROM user where id = ?`, userId, (err, row) => {
if (err) {
res.status(400).json({"error":err.message});
}
res.status(200).json(row);
});
});
module.exports = router
const express = require("express");
const app = express();
const router = require('./routes/users')
app.use(router)
// Server port
const PORT = 8000;
// Start server
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`)
});
const sqlite3 = require('sqlite3').verbose();
const DBSOURCE = "database.db"
let db = new sqlite3.Database(DBSOURCE, (err) => {
if (err) {
// Cannot open database
console.error(err.message)
throw err
} else {
console.log('Connected to the SQLite database...')
}
});
module.exports = db
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question