Home > Software engineering >  why similar routes is not working in express.js example Get ,post ,patch ,delete
why similar routes is not working in express.js example Get ,post ,patch ,delete

Time:04-27

Can any one help me only one route is working after adding second route

I am unable to trigger the second route getting error

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>Error</title>
</head>

<body>
    <pre>Cannot GET /api/sellProduct1</pre>
</body>

</html>

Note : Please don't suggest to change the route names , I am curious why they are not working with same routes but I am using different methods like post,get,delete. plz can any one can help with proper answer.

var mongoose = require('mongoose');
var express = require('express');
var router = express.Router();
var productModel = require("./productSchema");

// Connecting to database
var query = 'mongodb://127.0.0.1:27017/mylibs'
const db = (query);
mongoose.Promise = global.Promise;

mongoose.connect(db, {
    useNewUrlParser: true,
    useUnifiedTopology: true
}, function (error) {
    if (error) {
        console.log("Error!"   error);
    }
});

router.get("/", (req, res) => {
    res.send("welcome");
});

// find product by productname
router.get("/sellProduct:product", function (req, res) {

    productModel.findOne({ productName: req.query.product },
        function (err, data) {
            if (err) {
                console.log(err);
            }
            else {
                res.send(data);
            }
        });
});


router.post('/sellProduct', function (req, res) {
    var newProduct = new productModel({
        productName: req.body.productName,
        costPrice: req.body.costPrice,
        sellPrice: 0
    });

    newProduct.save(function (err, data) {
        if (err) {
            console.log(error);
        }
        else {
            res.send("Data inserted");
        }
    });
});

CodePudding user response:

You should access the routing this way:

/api/sellProduct/1

CodePudding user response:

The second route should be like this:

router.get("/sellProduct/:product")

and you can access product using req.params.product

So, to find the product inside db the query should be:

productModel.findOne({ productName: req.params.product })
  • Related