简体   繁体   中英

Edit and create HTML content using node.js

I want to create html content that looks something like this using node.js .

<div class="outputs">
   ...
</div>

I have the following code:

var mongoose = require("mongoose");
var express = require("express");
var bodyParser = require("body-parser");
var Url = require("./models/Url");
var shortId = require("shortid");
var http = require("http");
var app = express();
var { JSDOM } = jsdom;

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
mongoose.connect(process.env.MLAB_URI);

app.get("/urls", (req, res, next) => {
  Url.find({}, function(err, data) {
    res.json(data);
    console.log(data.length);
  });
});

app.get("/deletebase", (req, res, next) => {
  Url.deleteMany({}, function(err, data) {
    res.json(data);
  });
});

app.use(express.static(__dirname + "/"));

app.get("/:shortUrl", function(req, res, next) {
  Url.findOne({ shortUrl: req.params.shortUrl }, function(err, findUrl) {
    if (err) console.log(err);
    if (!findUrl) {
      return next({ status: 400, message: "unknown shorturl" });
    }
    res.redirect(findUrl.longUrl);
  });
});

app.post("/", function(req, res) {
  var url = new Url(req.body);
  var hostname = req.headers.host;
  var expression = /[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)?/gi;
  var regex = expression;
  if (regex.test(url) === true) {
    url.shortUrl = shortId.generate();
    url.fullUrl = "https://" + hostname + "/" + url.shortUrl;
    url.save(function(err, savedUrl) {
      if (err) console.log(err);
      res.redirect("https://" + hostname);
    });
  } else {
    res.redirect("https://" + hostname);
  }
});

var options = {
  runScripts: "dangerously",
  resources: "usable"
};

app.listen(3000, function() {
  console.log("RUNNING");
});

I want to get length of the data and create that many div objects with longUrl and shortUrl objects in it. Also when database will be updated new div object should be created, and when I delete database information all the div elements should be deleted too, is this possible to do?

You should be using a templating engine for this the two most popular ones for Node.js are pug(formerly Jade) and hbs(Handlebars.js) .

There are a lot of other template engines here you could consider.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM