I have the following URL:
http://localhost:3000/?url=test
In my routes/index.js I'm great the url parameter and trying to console.log:
var express = require('express');
var router = express.Router();
var url_param;
router.get('/:url', function (req, res) {
var url_param = req.params.url;
});
var url;
var url = url_param
console.log(url);
However it doesn't log anything. In my terminal I get it performing the GET function correctly:
GET /?url=test 304 4.169 ms - -
Am I missing something?
Thanks!
(I am guessing that this will work.) Try to write you console.log inside your function. Like
router.get('/:url', function (req, res) {
var url_param = req.params.url;
console.log(/* your code */ );
});
Here's how to store the value and use it somewhere else:
var express = require('express');
var router = express.Router();
var url;
// http://localhost:3000/url
router.get('/url', function(req, res) {
res.send("the stored url is " + url);
});
// http://localhost:3000/?url=x
router.get('/:url', function(req, res) {
url = req.params.url;
console.log(url);
res.send("url stored");
});
Why wouldn't it work outside the route.get function?
The moment you run 'node thisfile.js' everything on the script will be processed, however router.get function will be waiting to receive an event which will only be triggered once the url is visited.
Thus without the router.get function receiving an event url_param remains undefined. So to get the url param you need to visit the url it matches.
var express = require('express');
var router = express.Router();
var url_param;
router.get('/:url', function (req, res) {
url_param = req.params.url;
console.log(url_param);//TO BE HONEST This will work
});
console.log(url_param);//TO BE HONEST THIS WOULDNT WORK
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.