Nothing I do ever works… Someone cares to explain what’s wrong with this simple routing+mongo halfway implementation for the url shortener?
I found the solution in the forums but I want to understand why my way doesn’t work… I sometimes get 404, and sometimes " conn.openUri(…).then is not a function". I used the Express generator for the basic files.
/app.js:
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', shortenerRouter);
app.use('/shortUrl', getShortUrlRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
routes/index.js
const ShortUrls = require('../models/shortUrl');
const shortenerRouter = express.Router();
shortenerRouter.use(bodyParser.json());
/* GET home page. */
shortenerRouter.route('/')
.get(function(req, res, next) {
console.log(".get")
res.render('index', { title: 'Express' });
})
//send long url to get short url
.post(function (req, res, next) {
next()
});
module.exports = shortenerRouter;
/routes/getShortUrl.js:
const ShortUrls = require('../models/shortUrl');
const getShortUrlRouter = express.Router();
getShortUrlRouter.use(bodyParser.json());
//get short url return long url
getShortUrlRouter.route('/:shortUrl')
.get((req, res, next) => {
const url = 'mongodb://localhost:27017/UrlShortener';
mongoose.connect(url, {useNewUrlParser: true});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
console.log(".get :shortUrl: " + req.params.shortUrl);
ShortUrls.find({shortUrl: req.params.shortUrl}, (err, data)=>{
if (err) return console.error(err)
console.log(data)
res.send("long url: " + data);
})
})
next()
});
module.exports = getShortUrlRouter;
models/shortUrl.js:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
require('mongoose-currency').loadType(mongoose);
const shortUrlSchema = new Schema({
longUrl: String,
shortUrl: {type: String, unique: true}
})
var ShortUrls = mongoose.model('ShortUrls', shortUrlSchema);
module.exports = ShortUrls;