简体   繁体   English

使用 node.js 编辑和创建 HTML 内容

[英]Edit and create HTML content using node.js

I want to create html content that looks something like this using node.js .我想使用node.js创建看起来像这样的 html 内容。

<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.我想获取数据的长度并创建许多包含longUrlshortUrl对象的 div 对象。 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?另外,当数据库将被更新时,应该创建新的 div 对象,当我删除数据库信息时,所有的 div 元素也应该被删除,这可能吗?

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) .您应该为此使用模板引擎,Node.js 的两个最流行的引擎是pug(以前的 Jade)hbs(Handlebars.js)

There are a lot of other template engines here you could consider.还有很多其他的模板引擎在这里,你可以考虑一下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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