JohnSnow
JohnSnow

Reputation: 7121

app.get works, app.use does not

How come this is working:

app.get(/\/new\/(.*)/, function (req, res) {

    console.log(req.params[0]);
    res.json({site: req.params[0]});

});

but the same code won't if i use app.use().

const app = require("express")();
const error = require("./routes/error");

app.use(/\/new\/(.*)/,error);

error.js

const express = require("express");
const router = express.Router();


router.get("/",function(req,res){
    console.log(req.params[0])
    res.json({site:req.params[0]})
});




module.exports = router;

It just logs undefined to the console in this case, but in the first case it returns everything typed after the "new" route.

Upvotes: 1

Views: 165

Answers (1)

Pankaj kumar Panigrahi
Pankaj kumar Panigrahi

Reputation: 761

If you want to implement the same using app.use(), you have to modify your code slightly. Do the following changes:

In app.js:

app.use('/new',error);

and in error.js ,

router.get(/(.*)/,function(req,res){
    console.log(req.params[0])
    res.json({site:req.params[0]})
});

Try this and let me know

Upvotes: 3

Related Questions