express -e demo
change directory:
> cd demo
install dependencies:
> npm
run the app:
> SET DEBUG=demo:* & npm start
module.exports = {
mongo_base_connection_url: 'mongodb://localhost:27017',mongo_db: 'mongodb://localhost:27017/shorturl',mongo_options: {
autoReconnect: true,keepAlive: true,reconnectTries: 50,reconnectInterval: 1000,connectTimeoutMS: 5000000,}
}
console.log("Connection local mongo db");
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var urlSchema = new Schema({
shortUrl: String,longUrl: String
});
module.exports = mongoose.model('UrlTable',urlSchema);
var index = require('./routes/index');
var url = require('./routes/url');
app.use('/',index);
app.use('/url',url);
const express = require("express");
const router = express.Router();
const shortId = require('shortid');
const UrlTable = require('../models/urltable');
const mongoose = require('mongoose');
var setup = require('../dbconfig/db');
router.post('/',function(req,res,next) {
var params = req.body;
var url = params.longUrl;
shortId.characters(' 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ^*')
var shortid = shortId.generate();
var objurl = { shortUrl: shortid,longUrl: url};
mongoose.connect(setup.mongo_db,setup.mongo_options);
UrlTable.create(objurl,function (err,objurl) {
//if (err) console.log(err);
res.send("http://localhost:3000/" + shortid);
});
return;
});
const express = require("express");
const router = express.Router();
const UrlTable = require('../models/urltable');
const mongoose = require('mongoose');
var setup = require('../dbconfig/db');
router.get('/:shortUrl',function (req,next) {
var shortUrl = req.params.shortUrl;
mongoose.connect(setup.mongo_db,setup.mongo_options);
UrlTable.findOne({ shortUrl:shortUrl }).then((result) => {
//待添加错误处理
res.redirect(result.longUrl);
})
});
module.exports = router;