0

I am certain that this is super easy, but I can't for the life of me figure out why this does not work.

So trying to write an application where a user can search, gets a link, and if clocked it calls a second route, passing a variable while it is at it. Sounds simple, so thought I.

The idea is that each link generated gets a link like "localhost:3000/getcan/:[id]" So for our example, I am trying to get 22 into a variable if I try to go to webpage

"localhost:3000/getcan/:22"

To set up the route, I set the following in app.js

app.use('/getcan/:*', getcan);

This seems to work, and if I put anything that calls /getcan/: I go to the right route.

The route it self looks as follows

var express = require('express');
var router = express.Router();

/* GET getcan page. */
router.get('/', function(req, res, next) {
    var canid = req.params.canid;
    console.log("Got the following id " + canid)
    res.render('getcan', { title: 'ResourceEdge', reqcan: canid });
});

module.exports = router;

I think the problem is with router.get('/' but if I make any changes (tried get('/getcan/:canid) it all blows up with a 404.

Any pointers?

1 Answer 1

1

Change app.use to:

app.use('/getcan', getcan);

And your router to:

/* GET getcan page. */
router.get('/:canid', function(req, res, next) {
    var canid = req.params.canid;
    console.log("Got the following id " + canid)
    res.render('getcan', { title: 'ResourceEdge', reqcan: canid });
});

Then call your route using: http://localhost:3000/getcan/22

Sign up to request clarification or add additional context in comments.

4 Comments

That worked perfect. Can I ask a followup question, now that I have it in canid, how do I get access to it in the webpage (i.e it will render getcan, but I need a way to get the variable over to angular or javascript to get the data requested)
Well, if you're using something like angular, then you shouldn't be using render(). You should be serving static HTML and then using $http to call your Node routes, which would respond with some sort of data using res.json(). Using res.render() all you can really do is stick the variable into a script tag using a codeblock in whatever templating engine you're using
Ignoring what I should do at the moment, how would I do it if I wanted to? The content would not really be that good for single page app so really want to just load another page based on it:)
This could potentially be a difficult answer. I'd make a new question, indicating exactly what you want to do, including the code for the page you're rendering.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.