0

i've managed to connect nodejs with postgresql. my problem is this, when trying to retrieve,delete or update a single item, the url '/v1/:id' is not recognized by postman.it throw a cannot get,or cannot delete or update error. but, retrieving all the user items works well. I'm not supposed to use any ORM but pure sql. I've also checked everywhere on the internet with no proper solution or explanation to this. What could be the issue?

//here is my app.js file
const express = require('express');
const bodyParser = require('body-parser');
const pg = require('pg');
const route = require('./routes/user');
const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));

app.use('/v1',route)

module.exports = app;

//here is my controller file that handles the logic
const db = require('../db/config');



const getAllUsers = (req,res,next)=> {

 db.query('select * from users',(err,result)=>{
  if(err) {
   res.status(400).send('error in connection')
  }

  res.status(200).json(result.rows);
  console.log('this is the getusers route ')
 })
}

const getUserById = (req,res,next)=> {
 const id =parseInt(req.params.id);

 db.query('select * from users where id=$1',[id],(err,results)=>{
  if(err) {
   throw err
  }
  res.status(200).send(results.rows);
  console.log('successfully found id');
 })
}

//delete item

const removeItem = (req,res,next)=> {
 const id = parseInt(req.params.id);

 db.query('DELETE from users where id=$1',[id],function(err,result){
  if(err) {
   throw err
  }
  console.log('item deleted');
 })
}

module.exports = {getAllUsers,getUserById,removeItem}

//and here is my route file that handles all the routes
const express = require('express');
const router = express.Router();
const controller = require('../controller/user');



router.get('/',controller.getAllUsers);
router.get('/users/:id',controller.getUserById);
router.delete('/item/:id',controller.removeItem);


module.exports = router;

enter image description here

mohadennis
  • 21
  • 1
  • 8
  • `/:id` is not a valid URL. I presume that `:id` should be replaced with the actual id value. Plus your defined routes are `/users/someId` and `/item/someId`. – jfriend00 Nov 14 '19 at 08:14
  • Exactly as @jfriend00 said. In express, `:id` is replaced for whatever you put there, and you use that id with `req.params.id` (as you already did) see this question https://stackoverflow.com/questions/34095126/express-router-id – Slye Nov 14 '19 at 12:51

3 Answers3

0

:id should be treated as URL parameter

http://localhost:8000/v1/users/1234 -> where 1234 is your :id

I'm using POST on my test

enter image description here

Ed Bangga
  • 12,879
  • 4
  • 16
  • 30
0

enter image description here

id parameter is empty, please enter "id" here

Xander Le
  • 44
  • 5
0

From the screenshot of postman, seems like you missed to set the value for "id" under path variable.

vikash vik
  • 686
  • 5
  • 10