res.send() after res.redirect() in nodejs - node.js

I am trying to send a variable to the page after I have redirected to another page. I have very basic knowledge in Node.js and can't seem to figure out a way to do that. Here's my code.
app.get('/search' , function (req, res) {
var postcode = req.query.search;
var ward = my_search.getWardNum(postcode,(ward) => {
res.redirect('/:ward'+ ward);
});
});
app.get('/ws/:postcode' , function (req, res) {
var postcode = req.params.postcode.replace("+","");
console.log(pc);
my_search.postcodeLookUp(pc,(ward) => {
var area = my_search.lookupWard(ward);
res.send(area);
});
});
So in the first app.get(), I get the postcode and redirect to another page.
However, I still need that postcode with second app.get().
I understand that nature of node.js is async. Is there a way to do what I want to do?

When you "redirect", you're not just changing the URL the user sees, you're sending a HTTP response with a status code indicating that the client should try to access another page instead.
You can't send data after you redirect because the full response has already been sent! You should consider why you're redirecting and if it is really necessary. You could also redirect to a route containing the URL parameter that you want to be present:
res.redirect('/ward/' + ward + '/' + postcode);
...
app.get('/ward/:wardID/:postcode', (req, res, next) => {
// route code here...
});
Note that you'll probably want a prettier format than that, but that is one way to accomplish this.

Related

endpoint don't work, doesn't return anything

¿can you help me to understand this?
If I have an endpoint in a specific route it will display in the browser the expected content, but with the same code just modifying the endpoint it doesn't return anything.
The only change that I do is the route of the endpoint, the rest of code is the same in both cases.
¿Why this happen?
The code displays in the browser the content of a json file:
this way it doesn't work:
It doesn't show an error, just don't return anything.
localhost:3000/v1/people/partner
app.get("/v1/people/partner", (req, res) => {
const peopleInVisual = PeopleController.getAllVisualPeople();
res.json({ peopleInVisual });
});
In this way it works fine: notice I just have changed the hello at the endpoint
localhost:3000/v1/hello/partner
app.get("/v1/hello/partner", (req, res) => {
const PeopleInVisual = PeopleController.getAllVisualPeople();
res.json({ PeopleInVisual });
});
Thanks!

Axios - send get request with url + variable

This must be a stupid question, but I'm just starting and would appreciate any help!
So I have this code to get query parameter:
app.get('/', (req, res) => {
var code = req.query.code;
console.log(code);
And when I go to http://localhost:3000/?code=123, I get the code value in console, so it works fine.
Now, I need to send a GET request and add the value of the var code, this is where I'm stuck.
Let's say, I should send a GET request to 'http://testtesttest123.com/' + var code + 'hi'.
How can I do this?
I've tried this way and some other ways, but nothing worked:
axios.get('http://testtesttest123.com/?&code=', {params: {code}}, '&hi')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
});
Thank you in advance!
The axios.get call should look like this.
axios.get('http://testtesttest123.com/?code=' + code + '&hi')
With code = 123, this will call the URL http://testtesttest123.com/?code=123&hi.
Use the params config to send through query parameters. To support your empty hi parameter, you can include it in the URL string
axios.get("http://testtesttest123.com/?hi", {
params: { code }
})
For a code value of 123, this will perform a GET request to
http://testtesttest123.com/?hi&code=123
It will also ensure that the code value is made safe for use in URLs

How to handle missing param in route? Express

How do I handle a route that has a parameter, and if the client fails to include it, not let the server error out.
router.get('/:id', function(req, res, next) {
let profileID = req.params.id
if (profileID) {
res.send('ID provided');
} else {
res.send('No id provided');
}
});
If the ID parameter is provided I want to use it somewhere. But if it is missing, I want there to be a default behaviour to fall back to (ie. Route to another page, some message, etc)
The expected behavior is:
http://example.com/ routes to a landing page
But if a trailing ID is provided
http://example.com/abc123 routes to a specific profile
You can specify router.get('/:id?') and then id will be marked as an optional param.
CodeSandbox example
Express Server Example
// the question mark marks the parameter as optional
app.get("/:id?", (req, res) => {
// will create an id entry even if none is provided
console.log(req.params);
// if there is an id do something else
if (req.params.id) return res.send(req.params.id);
// if there is no id default behaviour for '/' route
res.sendFile(__dirname + "/view/hello.html");
});

Express routes - best way to make a url params.id serve static and dynamic content

Suppose I have a urls like
www.foo.com/abc
www.foo.com/huyr
... etc
where 'abc' and 'huyr' in this example are IDs, and i'd fetch info from the database where the key is that id.
But suppose I also want static links (that'll serve static pages) to follow the same url format:
www.foo.com/about
www.foo.com/contact
What would be the best way to do this?
Right now I have something like this in mind
exports.view = function(req, res) {
var id = req.params.id
switch (id) {
case 'about':
// load 'about' controller
break
case 'contact':
// load 'contact' controller
break
default:
// proceed with this function
}
}
Is this the best approach? is there a more efficient/organized way to do this?
Best way, in my opinion, would be to serve those pages, static or not, like you would with any other page. Respond to the GET request with the right page.
// will respond to http://www.site.com/about
app.get('/about', function( req, res, next ) {
res.render('about.ejs' // etc
});
// will respond to http://www.site.com/contact
app.get('/contact', function (req, res, next) {
res.render('contact.ejs' // etc
});
// will respond to any first subdir (iirc) http://www.site.com/(?)
app.get('/:id', function ( req, res, next ) {
var id = req.param['id'];
// db query, etc
});
You static pages of course can be in a route to make it cleaner. Only thing you need to make sure of is you respond to those static routes before the id route, or else you will be responding to the about/contact url with the route that you want responding to the ids. Order matters here.

Serving dynamic URLs with express and mongodb

I'm building a site that has somewhat reddit-like functionality. I want user-submitted content to get its own page. Each submission is assigned a 5 character ID that I want to be in the URL for that page.
I've got this function in the router file which renders a page called titles:
exports.titles = function(req, res){
i = 0
read(function(post){
url = post[i].URL;
res.render('titles', {title: post[i].title, url: post[i].URL});
});
};
It is served by this statement in app.js:
app.get('/titles', home.titles); //home.js is the router file
The titles page has a link with the text post.title and the URL post.URL. When a user clicks on the link (e.g. domain.com/12345) they should be taken to a page called content with the content post.body.
How do I a)pass the URL back to my app.js file to include in an app.get, b) include the app.get function in this router file, or c) solve this in any other way?
Edit: I do have an object 'titles' that is a mongodb collection, but it is in a different module. No reason I can't add it to the router though.
Edit: I tried adding this to app.js to see if it would work:
app.get('/:id', function(req, res){
return titles.findOne({ id: req.params.id }, function (err, post) {
if (err) throw(err);
return res.render('content', {title: post.title, content: post.body});
});
});
Edit: I got it to work. All I did was format the title so that it would look like domain.com/titles/12345 and change app.get('/:id', to app.get('/titles/:id, ...
If I get you right I would do that the other way around.
Short version
I would get the id from the URL
Then I would pull from the database the data associated with this id
And use this data to build the final page.
You don't need to create a new route for each URL. An URL can contain some variable (here the id) and Express can parse the URL in order to get this variable. Then from this id you can get the data needed to build the proper page.
Long version
I assuming someone type in this URL: http://domain.com/1234.
I also assume that you have a variable titles which is a MongoDB Collection.
You can have a route defined like this:
app.get('/:id', function(req, res) {
// Then you can use the value of the id with req.params.id
// So you use it to get the data from your database:
return titles.findOne({ id: req.params.id }, function (err, post) {
if (err) { throw(err); }
return res.render('titles', {title: post.title, url: post.URL /*, other data you need... */});
});
});
Edit
I made some changes according to the last comments...

Resources