redirect to a other view in node - javascript

I have a function that runs on a click, I want this click to redirect to a other view. like a simple link.
how can I render a new view onclick?
node
router.post('/shareinsight', function(req, res, next) {
console.dir(req.body)
var db = req.db_login;
console.log('fs' + req.body.date)
res.redirect('contact');
});
I can see the log in the console so I know that the function is running but it doesn't change view

Try to use this code:
router.post('/shareinsight', function(req, res, next) {
console.dir(req.body)
var db = req.db_login;
console.log('fs' + req.body.date)
res.writeHead(302, {
'Location': 'url'
});
res.end();
});

Related

Passing params through ui-router to the server

I have some troubles with geting single user basing on his ID. I can remove this certain user with DELETE in my app but I can't get informations about him using "GET".
this is my angular app.js
app.controller('editUser', function($scope, $http, $state) {
$http.get('users/editUser/'+$state.params.userId).success(function(data) {
console.log(data);
});
});
and this is my users.js routes file
router.get('/editUser/:userId', ensureAuthenticated, function(res, req, next) {
var userId= req.params.userId,
data;
getUser.findOne({'_id': userId}, function(err, user) {
if(err) throw err;
data = user;
res.json(data);
});
});
after clicking on "edit" button I am redirected to users/editUser/ffw23rfaw - its id, and basing on this id I use get function to get info about him but I get 500 "Internal server error". I would like to add that removing user is pretty much same and it works.
after clicking Edit button I do this
$scope.editUser = function($index) {
$state.go('editUser', {userId: $index});
}
that's how I get userId on 'users/editUser/' page
and this is my state config
.state('editUser', {
url: '/users/editUser/:userId',
templateUrl: '/views/editUser.html'
})
Found out the issue :)
Your code has function(res, req, next)
Change that to
function(req, res, next)
just wrong placement of parameters (variable names).
Hope this helps. (thanks for pointing out the console message)

GET in a Route - Nodejs

what´s the best way if I want to make a GET request in a route?
api.js
api.route('/guests')
.get(function(req, res) {
Guest.find(function(err, guests) {
if (err)
res.send(err);
res.json(guests);
});
});
routes.js
app.get('/export', requiresLogin, function(req, res) {
/* make a GET request to my api (eg.: 'api/guests') */
/* and save the 'guests' to a variable */
});
First Solution
Instead of calling internal apis, you can define a controller guestCtrl.js and call the function from guestCtrl.js in api.js and routes.js
guestCtrl.js
module.exports = {
getGuests : function(){
Guest.find(function(err, guests) {
if (err)
//handle error
return [];
else
return guests;
});
}
}
api.js
//path of guests.js
var guestCtrl = require('guestCtrl.js');
api.route('/guests').get(function(req, res) {
return guestCtrl.getGuests();
});
routes.js
var guestCtrl = require('guestCtrl.js');
app.get('/export', requiresLogin, function(req, res) {
var guests = guestsCtrl.getGuests();
// do whatever you like to do with guests
});
Second Solution
If you really want to work with internal api, then you can use request module.
e.g.
routes.js
var request = require('request');
app.get('/export', requiresLogin, function(req, res) {
// you can put the hostname and port here
request('http://127.0.0.1:3000/api/guests', function(err, body, response){
var guests = body; // and save the 'guests' to a variable
});
});

Node JS Routing URL Conflict

Each piece of this code works individually but when put together, the Article section (third set) will not load. I am fairly new to coding so I was hoping for someone to point me in the right direction. I assume this is because the first route is executed and it never hits the second route...but I don't know how to fix it.
// Adds "www." to all URLs
app.all('*', function(req, res, next) {
if (req.headers.host.match(/^www/) == null) {
res.redirect('http://www.' + req.headers.host + req.url);
} else {
next();
}
});
// Serves the .html file but displays without .html in the URL
app.get('*', function(req,res){
var pages = ['/now', '/home', '/itinerary','/exploreourroots','/contact','/credits'];
if (pages.indexOf(req.url.toLowerCase()) !== -1) {
res.sendFile(__dirname + '/public' + req.url + '.html');
};
});
// Loads Articles from the database on the home page
app.get('/home', function(req, res) {
var query = 'SELECT a.title,a.author,a.cover_photo,a.html_loc,a.date_published,c.name country_name FROM articles a INNER JOIN countries c ON c.id=a.country_id ORDER BY a.date_published desc;'
connection.query(query, function(err, rows, fields) {
var list = [];
for (var i = 0;i < rows.length; i++) {
list.push({html_loc: rows[i].html_loc,country_name: rows[i].country_name,cover_photo: rows[i].cover_photo,title: rows[i].title,author: toAuthorPhoto(rows[i].author),date_published: toArticleDate(rows[i].date_published)});
}
res.contentType('application/json');
res.send(list);
});
});
Thanks for the help!
I'm not sure what intentions you have.
What if user type in browser www.mydomain.com/home. You want to return static html file (home.html), which is done by second router. Or you want to serve then article from db (third route)?
If you want to serve article from db when url is /home, then replace order of second and third routes:
app.get('/home', function(req, res) { ... });
app.get('*', function(req,res){ ... });
if you want to serve static html when your route is /home and also you want to have possibility to serve articles, then as before replace orders and additionally change /home router to /article. Then you will serve articles if url is /article :
app.get('/article', function(req, res) { ... });
app.get('*', function(req,res){ ... });

Node.js Express : How to redirect page after processing post request?

How to redirect to different page from post request ?
module.exports = function(app) {
app.post('/createStation', function(request, response){
response.redirect('/'); //This doesn't work, why and how to make this work
/*var stationDao = require('./server/stationDao.js');
stationDao.stationDao.createStation(request.body, function(status){
if(status.status == 'successful'){
response.redirect('/'); //This is what actually I wanted to do
}*/
});
});
};
Tried using next() as well,
app.post('/createStation', [function(request, response, next){
var stationDao = require('./server/stationDao.js');
stationDao.stationDao.createStation(request.body, function(status){
if(status.status == 'successful'){
next();
}
});
}, function abc(request, response){
console.log('I can see this');
response.redirect('/'); //This doesn't work still
}]);
It actually triggers the GET request but the page won't redirect.
Since I am new in node.js, any kind of suggestion for the above code would be appreciated.
I suggest you to leverage next, so something like
app.post('/', handlePostOnRoot);
app.post('/createStation', [
function(req, res, next){
next()
},
handlePostOnRoot
]);
On the subject: http://expressjs.com/guide/routing.html#route-handlers
EDIT based on comment:
I've just wrote a really basic server to test what I wrote:
var express = require('express');
var app = express();
app.post('/a', [function(req, res, next) {
next();
}, function(req, res) {
res.send('Hello World!');
}]);
var server = app.listen(3000, function () { console.log('listening'); });
This works for me, I would encourage you to run that and then curl -X POST http://localhost:3000/a, in my case I correctly got "Hello World!".
If this also works for you try to isolate your problem a bit more by removing some bits and pieces.
Not an expert in Angular, but from what I can find, the form won't automatically follow the / redirect after doing the POST. Instead, people recommend using Angulars $location.path('/'); to do a manual redirect after the form was submitted.

Routing issue, not collecting req.params

I am making a wikipedia clone for a project. My initial edit Route looks like this:
router.get('/edit/:id', function(req, res){
var id = req.params.id;
console.log(id);
models.Page.findById(id, function(err, doc){
console.log(doc);
res.render('edit', {page: doc});
});
});
All I am doing is creating an edit page view for a Page with matching id of the id params.
This works until...
I had to add this new route:
router.get('/:url_name/:id', function(req,res){
var id = req.params.id;
models.Page.findById(id, function(err, doc){
res.render('show_page', {page: doc});
});
});
Now when I have this route active, my edit/:id page route doesn't collect the id parameter(req.params.id).
I am lost on why this isn't working and where I should start trying to debug because I am not getting any errors, it will still take me to my edit/:id page, but when I console.log(id) I do not receive a value, or even and undefined, nothing. Furthermore, the {page:doc} I am passing to my edit view is not being found.
If anyone can provide insight or a place to start looking to debug, I'd appreciate it. Just a reminder, the edit/:id route works as it should (req.params.id grabs the id) when I don't have the :url_name/:id route active.
Current Routes -
I added var wiki_routes = require('./routes/wiki'); in my app.js and in that route I have:
// **** URL ROUTES ****
router.get('/', function(req, res) {
models.Page.find(function(err, docs) {
res.render('index', { docs: docs });
});
});
router.get('/:url_name', function(req, res){
var url_name = req.params.url_name;
var isUpdated = req.query.updated;
var updated = (isUpdated === 'true')?true:false;
models.Page.find({url_name: url_name}, function(err, page){
if(page.length > 1){
console.log(page);
res.render('disambiguation', {pages: page, updated: updated });
} else {
console.log(page);
res.render('show_page', {page: page[0], updated: updated});
}
});
});
router.get('/:url_name/:id', function(req,res){
var id = req.params.id;
models.Page.findById(id, function(err, doc){
res.render('show_page', {page: doc});
});
});
// **** EDIT ROUTES ****
router.get('/edit/:id', function(req, res){
var id = req.params.id;
console.log(id);
models.Page.findById(id, function(err, doc){
console.log(doc);
res.render('edit', {page: doc});
});
});
router.post('/edit_submit/:id', function(req, res){
var id = req.params.id;
var new_title = req.body.title;
var new_body = req.body.body;
console.log(req.body);
models.Page.findByIdAndUpdate(id, {title: new_title, body: new_body }, function(err, docs){
// redirects to the wiki page
res.redirect('/wiki/'+ docs.url_name +'?updated=true');
});
});
// **** DELETE ROUTE ****
router.get('/delete/:id', function(req, res){
var id = req.params.id;
models.Page.findByIdAndRemove(id, function(err, data){
res.redirect('/?deleted=true');
});
});
Routes are set up as they occur in the code, as node will give presedence to whichever route it encounters first, so order matters a lot when you're setting up your routes.
An URL could potentially match several routes, especially when using variables that catch a large number of different URL's, or static routes etc.
Say in your case you have an URL that looks like
http://example.com/edit/1234
That URL would most certainly be caught by this route
router.get('/:url_name/:id' ....
as it matches the http://example.com/something/something layout, and it would also be caught by the following route
router.get('/edit/:id', ....
as it matches the http://example.com/edit/something layout.
What route actually cathes the URL depends on the order they where encountered when set up, whichever route that was declared first will catch the URL.
Just shifting the order of the routes will in most cases solve issues like this
// if the URL matches, this will execute first
router.get('/edit/:id', function(req, res){
// do stuff
});
// You'll only get here if the URL doesn't match the above route
router.get('/:url_name/:id', function(req, res){
// do stuff
});
There is a workaround if you simply can't swap the routes around, using the next() callback, like this
router.get('/:url_name/:id', function(req, res, next){
if ( req.params.url_name == 'edit' ) {
next(); // this sends the request back to look for routes below this one
}else{
// do stuff
}
});
router.get('/edit/:id', function(req, res){
// now we'll get here when the "url_name" is "edit" ...
});

Categories

Resources