Home > Net >  Passing query parameter in nodejs but route is giving error
Passing query parameter in nodejs but route is giving error

Time:12-12

I want to pass the query parameter in the route. I used authentication middleware.

I want to delete a task based on that task id. Later I want to pass auth into delete by id route and allow the user to delete a task by authentication, but when I pass the query parameter the endpoint fails. If no query parameter is passed everything works fine.

task.js

const express = require('express')
require('../mongoose')
const Task = require('../model/task_model')
const auth = require('../middleware/user_middleware')
const router = new express.Router()

router.delete('/tasks/del/:id', async (req, res) => {
    try {
        const task = await Task.findByIdAndDelete(req.params.id)

        if (!task) {
            res.status(404).send()
        }

        res.send(task)
    } catch (e) {
        res.status(500).send()
    }
})

module.exports = router

index.js

const express = require('express')
const UserRouter = require('./router/user')
const TaskRouter = require('./router/task')

const app = express()
const port = process.env.PORT || 3000

app.use(express.json())
app.use(UserRouter)
app.use(TaskRouter)

app.listen(port,()=>{
    console.log('Server listening on port: '   port)
})

middleware.js

const jwt = require("jsonwebtoken")
const User = require("../model/user_model")

const auth = async function(req,res,next){
    try {
        const token = (req.headers.authorization).split(' ')[1]
        const decoded_token = jwt.verify(token,'ankan123')
        const user = await User.findOne({_id:decoded_token._id,"tokens.token":token})
        if (!user){
            throw new Error()
        } 
        req.user = user
        req.token = token
        next()
    } catch(e){
        res.status(400).send("PLease Authenticate")
    }
}

module.exports = auth

task_model.js

const mongoose = require('mongoose')

const TaskSchema = new mongoose.Schema({
    task: {
        type: String,
        required:true,
    },
    completed:{
        type: Boolean
    },
    creator:{
        type: mongoose.Schema.Types.ObjectId,
        required:true
    }

})

const tasks = mongoose.model('Task', TaskSchema)

module.exports = tasks

user.js

const express = require('express')
require('../mongoose')
const User = require('../model/user_model')
const auth = require('../middleware/user_middleware')
const router = new express.Router()
router.post('/users/login', async (req, res) => {
    try {
        const user = await User.matchCred(req.body.mobileNo, req.body.password)
        const token = await user.generateToken(user._id)
        return res.status(200).send({
            user,
            token
        })
    } catch (e) {
        res.status(400).send()
    }
})

module.exports = router;

I am getting route containing /tasks/del/:id does not exist when using postman to send delete requests. Postman Request

Mongodb task Collection

CodePudding user response:

The issue is simple you are passing it as query parameters, but it is path parameters. You can run like this in the postman:

{url}/tasks/del/'yourID' 

When you pass id as query parameters, it won't be able to match the path and hence you are receiving an error Can't Delete. I would say you should understand diff b/w them and you can check this link.

  • Related