I am using node and express for a web app.
I'd like to add a tag to my url when someone clicked on it but on the server side:
exports.route = function (state) {
return function (req, res) {
// here I'd like to add a line of code that will turn
// my url from 'http://path/index' to 'http://path/index?param=myParams'
res.render('index', {myParams});
};
};
How can I do this?
Many thanks
You could use a simple redirect:
if(!req.params.param) return res.redirect(req.url+'?param='+myParams);
If the querystring parameter is not defined or doesnt have the value you want, just redirect the user to the same url but with the parameter.
Related
Trying to write a simple route, getting a record by it's id property/column
const router = require("express").Router();
router.get("/record/:id", getRecordById) // CHANGE HERE
This is how I'm able to use for frontend ajax -
http://localhost:3001/record/1
What do I need to change, to be able to use the route as
http://localhost:3001/?record=1
You should create a route like this.
router.get("/", function (req, res) {
// Get record id
const record_id = req.query.record;
});
In your case
API:
router.get("/record", getRecordById)
URL:
http://localhost:3001/record?id=1
Get the query string in api:
req.query.id
I have an Express server, where my app is served from the app.get('*') route.
I'd like to have users with promo codes visit the site from a campaign URL like so: www.mysite.com/?code=123.
The problem is every browser request is routed to the favicon request, thus my req.url and req.query variables cannot be used to get the promo codes. Req.url is always /favicon.ico and req.query is always empty.
I did find the original URL is the request object's header, but this seems like a roundabout way of achieving my objective. The request object's original URL field also points to favicon.ico.
app.get('*', (req, res) => {
console.log(req.url);
console.log(req.query);
}
I'd like to keep my promo code solution as quick and dirty as possible for the time being, so I'm fine with URL parameters. Is there a simple solution to extract the original URL query parameters without diving into the headers?
EDIT: I'm now sharing my root request handler below. The favicon request is handled by the express-favicon middleware earlier in the code.
app.get('*', (req, res) => {
console.log("In get *");
console.log("Req.url: ",req.url);
console.log("Promo code: ",req.query.promo);
const context = {};
const app = ReactDOMServer.renderToString(
<StaticRouter location={req.url} context={context}>
<App />
</StaticRouter>
);
const indexFile = path.resolve('./public/index.html');
fs.readFile(indexFile, 'utf8', (err, data) => {
if (err) {
console.error('Something went wrong:', err);
return res.status(500).send('Oops, better luck next time!');
}
return res.send(
data.replace('<div id="root"></div>', `<div id="root">${app}</div>`)
);
});
})
The problem is that I'm using React Router, which doesn't support query parameters:
https://reacttraining.com/react-router/web/example/query-parameters
To get aroud this, I'm using window.location.search on the client to get the promo code, then passing to the backend with an explicit promo handler.
You can accept dynamic value as part of the URL in express
api call ==> www.mysite.com/dynamic_promo_code
app.get('/:promo_code',(req,res)=>{
// req.params will be and object holding your dynamic promo_code
const promo = req.params.promo_code; // this will be your dynamic promo code
});
if you wish your promo code is opitional and don't want to be part of URL
api call ==> www.mysite.com?promocode=dynamic_promo_code
app.get('/',(req,res)=>{
//req.query is an object holding your optional parameter
const code = req.query.promocode; // this will be yor dynamic promo code
})
I'm trying to redirect to the home page after a user hit this route: /ref=123 but I want to keep that baseUrl, this is what I have so far:
I am requiring in my server.js file this: const referred = require('./routes/referred').
app.use('/ref=:id', (req, res, next) => {
res.locals = req.params.id
}, referred)
So, when a user hits the above route I am doing some validations in my referred.js file. Actually I need to send some kind of response telling whether that provided id exist or not but showing anyways the home page which is a simple login/resgistration form.
referred.get('/', (req, res, next) => {
//doing validations with res.locals
next() //<- calling the next middleware
})
after calling next() I put that middleware just below to redirect to the home page.
not sure if this is possible: app.use(express.static(_dirname + '/dist')) it seems like is not because I'm getting a 404 .
I know I could use the req.redirect() function but that will actually made a new request to the server and refresh the page erasing the baseUrl that I want to keep up there.
How do you render/send your pages?
You could use res.sendFile('path/to/page.html') to send back any html file while keeping the request URL.
If you want to display a dynamic message on the home page, you should use a viewing engine like ejs. If you are already using an engine, you can do something like
res.render('path/to/page', { status: 'This id does not exist!'})
I'm just really new on Node and Express. Trying to pass a function instead of text on my route but it seems not working. I just looked up at documentation there, They mentioned only text with req.send() method. I'm trying to pass here function's but it's not working. and also the alert() not working like this req.send(alert('Hello world')) it say's alert isn't defined or something similar.
**Update: ** I'm trying to execute this library with express and node https://github.com/przemyslawpluta/node-youtube-dl
I'm trying to do here pass functions like this
function blaBla() {
var youtubedl = require('youtube-dl');
var url = 'http://www.youtube.com/watch?v=WKsjaOqDXgg';
// Optional arguments passed to youtube-dl.
var options = ['--username=user', '--password=hunter2'];
youtubedl.getInfo(url, options, function(err, info) {
if (err) throw err;
console.log('id:', info.id);
console.log('title:', info.title);
console.log('url:', info.url);
console.log('thumbnail:', info.thumbnail);
console.log('description:', info.description);
console.log('filename:', info._filename);
console.log('format id:', info.format_id);
});
}
app.get('/', (req, res) => {
res.send(blaBla());
})
**Instead of **
app.get('/', function (req, res) {
res.send('Hello World!')
})
I hope you guy's understood my question.
res.send() expects a string argument. So, you have to pass a string.
If you want the browser to execute some Javascript, then what you send depends upon what kind of request is coming in from the browser.
If it's a browser page load request, then the browser expects an HTML response and you need to send an HTML page string back. If you want to execute Javascript as part of that HTML page, then you can embed a <script> tag inside the page and then include Javascript text inside that <script> tag and the browser will execute that Javascript when the page is parsed and scripts are run.
If the route is in response to a script tag request, then you can return Javascript text as a string and you need to make sure the MIME type appropriately indicates that it is a script.
If the route is in response to an Ajax call, then it all depends upon what the caller of the Ajax call expects. If they expect a script and are going to execute the text as Javascript, then you can also just send Javascript text as a string. If they expect HTML and are going to process it as HTML, then you probably need to embed the <script> tag inside that HTML in order to get the Javascript executed.
In your example of:
response.send(blaBla());
That will work just fine if blaBla() synchronously returns a string that is formatted properly per the above comments about what the caller is expecting. If you want further help with that, then you need to show or describe for us how the request is initiated in the browser and show us the code for the blaBla() function because the issue is probably in the blaBla() function.
There are lots of issues with things you have in your question:
You show req.send(alert('Hello world')) in the text of your question. The .send() method belongs to the res object, not the req object (the second argument, not the first). So, that would be res.send(), not req.send().
In that same piece of code, there is no alert() function in node.js, but you are trying to execute it immediately and send the result with .send(). That won't work for a bunch of reasons.
Your first code block using blaBla() will work just fine as long as blaBla() returns a string of the right format that matches what the caller expects. If that doesn't work, then there's a problem with what blaBla() is doing so we need to see that code.
Your second code block works because you are send a string which is something the caller is equipped to handle.
Update now that you've shown the code for blaBla().
Your code for blaBla() does not return anything and it's asynchronous so it can't return the result. Thus, you cannot use the structure response.send(blaBla());. There is no way to make that work.
Instead, you will need to do something different like:
blaBla(response);
And, then modify blaBla() to call response.send(someTextValue) when the response string is known.
function blaBla(res) {
var youtubedl = require('youtube-dl');
var url = 'http://www.youtube.com/watch?v=WKsjaOqDXgg';
// Optional arguments passed to youtube-dl.
var options = ['--username=user', '--password=hunter2'];
youtubedl.getInfo(url, options, function(err, info) {
if (err) {
res.status(500).send("Internal Error");
} else {
console.log('id:', info.id);
console.log('title:', info.title);
console.log('url:', info.url);
console.log('thumbnail:', info.thumbnail);
console.log('description:', info.description);
console.log('filename:', info._filename);
console.log('format id:', info.format_id);
// construct your response here as a string
res.json(info);
}
});
}
Note also that the error handling does not use throw because that is really not useful inside an async callback.
No one just could help me with that and after finding things are alone I got to know how to do this. In express there is something called middleware we have to use that thing to get this kind of matter done. Those who are really expert or have working experience with express they know this thing.
to using functions with express you need to use middleware.
like below I'm showing
const express = require('express')
const youtubedl = require('youtube-dl');
const url = 'https://www.youtube.com/watch?v=quQQDGvEP10';
const app = express()
const port = 3000
function blaBla(req, res, next) {
youtubedl.getInfo(url, function(err, info) {
console.log('id:', info.id);
console.log('title:', info.title);
console.log('url:', info.url);
// console.log('thumbnail:', info.thumbnail);
// console.log('description:', info.description);
console.log('filename:', info._filename);
console.log('format id:', info.format_id);
});
next();
}
app.use(blaBla);
app.get('/', (request, response) => {
response.send('Hey Bebs, what is going on here?');
})
app.listen(port, (err) => {
if (err) {
return console.log('something bad happened', err)
}
console.log(`server is listening on ${port}`)
})
And remember that you must need to use app.use(blaBla); on top of getting your route. Otherwise this might not work.
I am working with node/express/passport/ looking at code that attempts to use a request like:
req._parsedUrl.pathname;
I cannot figure out where this variable is coming from. Is this a canonical variable name that is set in a common .js library? It doesn't seem exposed in any headers.
req._parsedUrl is created by the parseurl library which is used by Express' Router when handling an incoming request.
The Router doesn't actually intend to create req._parsedUrl. Instead parseurl creates the variable as a form of optimization through caching.
If you want to use req._parsedUrl.pathname do the following instead in order to ensure that your server doesn't crash if req._parsedUrl is missing:
var parseUrl = require('parseurl');
function yourMiddleware(req, res, next) {
var pathname = parseUrl(req).pathname;
// Do your thing with pathname
}
parseurl will return req._parsedUrl if it already exists or if not it does the parsing for the first time. Now you get the pathname in a save way while still not parsing the url more than once.
You can write a middleware to handle then set properties for req.
var myMiddleWare = function () {
return function (req, res, next) {
req._parsedUrl = 'SOME_THING';
next()
}
};
app.get('/', myMiddleWare, function (req, res) {
console.log(req._parsedUrl); // SOME_THING
res.end();
})
Express middleware document in here