retrieving var from URL - javascript

I'm visiting a link to my Node app called
http://localhost:5000/payment?issue=123456
In my node app i have a callback that is fired when this happens
app.get('/payment', function(req, res){
res.render('payment', { user: req.user });
});
how do i get the issue number (123456) and assign it to a variable in the node app?

To get the URL params, you can use a module called "url",
var url = require('url');
var url_parts = url.parse(request.url, true);
var query = url_parts.query;
As an Express only alternative you can use the req.query method
app.get('/payment', function(req, res){
issue = req.query.issue;
// Other stuff
});

Related

Ajax - GET method doesn't send params

Here's my request:
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "/api/registerRequest?user=user", true);
xhttp.send();
And here's the request being handled:
var express = require("express");
var router = express.Router();
router.get("/registerRequest/:user", function(req, res, next){
console.log("response for param");
console.log(req.params.user);
});
router.get("/registerRequest", function(req, res, next){
console.log("normal response");
console.log();
});
And here's the app:
var express = require("express");
var app = express();
app.use("/api", index);
Note that these are just small, relevant to the question, portions of the code.
Now, the output in the console is
normal response
But from my understanding, it should be:
response for param
user
You're misunderstanding routing.
router.get("/registerRequest/:user" matches URLs of the form /registerRequest/..., where ... becomes req.params.user.
You aren't making such a URL.
In the url /api/registerRequest?user=user, you are sending user as a query parameter. Which will allow you to access it from req.query.user. more here
In order to access it from req.params.user, you'll need to change the url in the ajax request to /api/registerRequest/user. doc reference

nodejs variable scope issue

I have a nodejs route where I am trying to download a url as mp3 using npm-youtube-dl. I have a download directory that I watch with chokidar for files being added and when a file is added I save the link to the file and after the download finishes I call a function that's supposed to respond with the download URL using res.download. When the sendURL function is called the url that I can clearly see has been saved before is undefined when I console.log it... Any idea what i'm doing wrong here/how I can fix this? i'm guessing it's a js variable scope issue?
my code:
var express = require('express');
var router = express.Router();
var yt = require('youtube-dl');
var fs = require('fs');
var path = require('path');
var chokidar = require('chokidar');
var downloadPath = '';
var watcher = chokidar.watch('./downloads', {
ignored: '/^[^.]+$|\.(?!(part)$)([^.]+$)/',
persistent: true
});
watcher.on('add', function(path) {
console.log('added: ', path);
this.downloadPath = path;
console.log('saved', this.downloadPath);
});
/*
router.get('/', function(req, res, next) {
next();
});
*/
router.get('/', function(req, res) {
var url = 'https://soundcloud.com/astral-flowers-music/bella-flor';
var options = ['-x', '--audio-format', 'mp3', '-o', './downloads/%(title)s.%(ext)s'];
var video = yt.exec(url, options, {}, function exec(err, output) {
if (err) { throw err; }
console.log(output.join('\n'));
sendUrl();
});
function sendUrl() {
console.log(this.downloadPath);
//res.download(this.downloadPath);
}
});
module.exports = router;
You're misusing this. If you want to use the downloadPath variable in your functions, remove the this. from in front of them. this.downloadPath looks for a property called downloadPath on an object referenced by this, which is different from your module-global variable.
More: How does the "this" keyword work?
Even with that, you're relying on your add callback having been called before any client requests your / route, and you're returning the last value assigned to downloadPath by that add callback. I don't know enough about what you're doing to know whether that's correct, but the lack of coordination seems problematic.

Console Log URL Parameter in routes/index.js

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");
});
move the console.log() inside the route.get function.
Even though you have to move the console.log(); already inside your router function you declared a different variable var url_param by so doing they don't have same reference.
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

Pass a parameter to another JavaScript and run the script

Send a parameter(URL) from another script through recursion to this script.
var express = require('express');
var request = require('request');
var cheerio = require('cheerio');
var mongodb = require('mongodb');
var app = express();
var MongoClient = mongodb.MongoClient;
// Connection URL. This is where your mongodb server is running.
var murl = 'mongodb://localhost:27017/getData';
url = '';
app.get('/getData', function(req, res){
firstCall(req,res)
//console.log("cookie",req.cookies);
})
var firstCall = function(req, res, data){
console.log("URL: ", url);
res.send('Check your console!');
}
app.listen('3000')
console.log('Magic happens on port 3000');
module.exports = function(app) {
app.get('/getData', function() {});
};
I want this code to act as backbone or logic board. And some other file should be able to trigger this logic board file by adding the URL to this file.
Like we pass parameters to function to call. How do I do it here.

Node.js: Using Socket.io in an express.js route to send message to a specific client

I have made a very casual commenting system, and now I want to add replies. So, when someone posts a reply on someone else's comment, that user must be notified that someone replied to their comment. In order to do that, when the replier clicks the reply button an AJAX post request is made to the server, the server then needs to get the id of the first commenter and send them a response text using socket.io (socket.io is not required to be used if there is another way to send the reply text with another module or express itself). This is my code so far:
app.post('/reply', function(req, res){
var commenterId = req.body.userId; // this is the id of the original commenter, not the replier
User.findOne({'_id':commenterId}, function(err, user){
user.send({'replied': req.user._id}); // this is what I need to do, and
//I don't know if this specific code works and that's why I'm asking if there is a way to do it with socket.io,
// io.to(socketId).emit('reply', 'some reply text here...'); // but if I do this I don't know how to get the socketId!
//Is there even a way to do this? Maybe with another module,
//or some express function I don't know about? And if it is done with express how would
//the client side code, look like? Thank you!
});
res.end();
});
//app.js file
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
var routes = require('./routes/routes')(io);
app.use('/', routes);
//router file
var express = require('express');
var router = express.Router();
var _socket = null;
//list of socket users.once they logout delete the socket by
//delete users[_socket.userid];
var users = {};
var returnRouter = function(io) {
io.sockets.on('connection', function (socket) {
//now _Socket is available inside routes
_socket = socket;
});
router.post('/login', function(req, res) {
//authentication logic
User.findOne({'email': req.body.email}, function (err, user) {
//userid must be unique
_socket.userId= user.userId
//set session variable to store id of the user
req.session.userId = user.userId;
//now every user has a socket associated with their id
users[_socket.userId] = _socket;
});
});
router.post('/reply', function (req, res) {
var commenterId = req.body.userId;
User.findOne({'_id': commenterId}, function (err, user) {
// you can get the id of the logged in user that is the creator
//of the original post from req.session.userId
//if you have implemented session store
//the commenter user object is obtained from findOne method
users[req.session.userId].emit('notification', {
notification: user.username+' commented on your post'
}});
});
res.end();
});
return router;
};
module.exports = returnRouter;

Categories

Resources