Skip to content Skip to sidebar Skip to footer

How Do I Redirect To Another Page Like Google Using Nodejs?

I am trying to get a number that will be stored in short variable. Then I look up on the database for a specific shortUrl that matches that number. If I find it I want the response

Solution 1:

Try this code.This works like charm!!!!!!. Firsrt create a models folder and place this file in it shortUrl.js

var mongoose = require('mongoose');
varSchema = mongoose.Schema;
varUrl = newSchema({
    shortUrl:
    {
        type : Number
    },
    url:
    {
        type : String
    }
        });

module.exports = mongoose.model('url', Url);

Next create a routes folder place this file in it urls.js

var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var shortUrl = require('../models/shortUrl');
var app = express();
var url = express.Router();
url.use(bodyParser.json());
url.route('/:short')
.get( function(req, res){
    var short = req.params.short;
     shortUrl.find({shortUrl: short}).then(function(result){

        var urlSearch = result[0]["url"];
        res.redirect('https://'+urlSearch) //DOESNT WORK
});
});
url.route('/num')
.post(function(req,res){
      shortUrl.create(req.body,function(err,url){
if (err) returnconsole.log(error); 
        return res.send(url);
     });

})
    app.use('/url',url);


module.exports = url;

Next create a config file so that you can give connections config.js

module.exports = {
    'secretKey': '12345-67890-09876-54321',
    'mongoUrl' : 'mongodb://localhost:27017/redirect'
}

And now create a server file like express.js

var express = require('express');
    var passport = require('passport');
    varLocalStrategy = require('passport-local').Strategy;
    var config = require('./config');
    var mongoose = require('mongoose');
    mongoose.Promise = require('bluebird');
    mongoose.connect(config.mongoUrl);
    var db = mongoose.connection;
    db.on('error', console.error.bind(console, 'connection error:'));
    db.once('open', function () {

        console.log("Connected correctly to server");
    });

    var app = express();

    var url = require('./routes/url');

    var shortUrl = require('./models/shortUrl');
    app.use('/url',url);

    app.listen(3000,function(){
    console.log("Server listening on port 3000");
    });

Output : Run the code as node express.js

Whenever you want to post use http://localhost:3000/url/num and give the details in json format.Whenever you want to get i.e.,redirect to aany page use http://localhost:3000/url/:shrot.Here :short nothing but a number should be passed a parameter.Hope this helps for you.

Solution 2:

Try this solution

res.writeHead(301,
  {Location: 'http://whateverhostthiswillbe.com'}
);
res.end();

Post a Comment for "How Do I Redirect To Another Page Like Google Using Nodejs?"