I got this far but I am stuck again…
under “find url” section, I want to use the data that I got (like let redirectUrl = data.original_url
) but it returns undefined
when I check with console.log.
Is there any way that I can get the redirectURL by the number that is entered in the URL?
'use strict';
var express = require('express');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var cors = require('cors');
var app = express();
// Basic Configuration
var port = process.env.PORT || 3000;
/** this project needs a db !! **/
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true }, (error, client) => {
console.log("Successfully connected to MongoDB");
})
// var MongoClient = require('mongodb').MongoClient;
// var url = process.env.MONGO_URI;
// MongoClient.connect(url, function(err, db) {
// if (err) throw err;
// console.log("Database created!");
// db.close();
// });
app.use(cors());
/** this project needs to parse POST bodies **/
// you should mount the body-parser here
const bodyParser = require('body-parser');
app.use('/public', express.static(process.cwd() + '/public'));
app.get('/', function(req, res){
res.sendFile(process.cwd() + '/views/index.html');
});
app.use(bodyParser.urlencoded({ extended: false }))
//crete model
const Schema = mongoose.Schema;
const urlSchema = new Schema({
original_url:{type:String,required:true},
shortid: { type: Number},
});
let Url = mongoose.model('Url', urlSchema);
app.post('/api/shorturl/new', (req, res) => {
let originalUrl = req.body.url;
let number = Math.floor(Math.random()*10000).toString();
//create new url
let newUrl = new Url({
original_url:originalUrl,
shortid: parseInt(number),
}
);
// //save new url
newUrl.save(function(err, data){
if (err)
throw err
});
console.log("newurl:"+newUrl)
res.send({"original_url":newUrl.original_url,"short_url":newUrl.shortid});
})
app.get('/api/shorturl/new/:number?', function(req, res){
let number = req.params.number
console.log("number:" + number)
//find url
let findUrl = function(n, done) {
Url.findOne( {shortid: n}, function (err, data) {
if (err) {
throw err
} else {
console.log("data:"+data);
let redirectUrl = data.original_url
console.log(redirectUrl)
}
});
};
findUrl(number)
res.redirect(redirectUrl);
});
app.listen(port, function () {
console.log('Node.js listening ...');
});