做了一个app,返回三国武将的排序网页,记录一下,省得以后找不到

这个app可以说是自己弄着玩的。

效果这样:

做了一个app,返回三国武将的排序网页,记录一下,省得以后找不到_第1张图片

 

 随机返回800多个三国武将里面的5个,然后按照这5个的武力值排序,渲染到list页面。挺好玩的。

使用nodejs和mogoose

app如下:

app.js

var createError = require("http-errors");
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");
const template = require("art-template");

var indexRouter = require("./routes/index");
var usersRouter = require("./routes/users");
var listRouter = require("./routes/list");
var testRouter = require("./routes/test");

var app = express();

// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "html");
app.engine("html", require("express-art-template"));

app.set("view engine", "art");
app.engine("art", require("express-art-template"));

app.locals.students = [
    { name: "张三", age: 20, sex: "女", like: "python" },
    { name: "李四", age: 20, sex: "男", like: "node" },
];

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("/", indexRouter);
app.use("/users", usersRouter);
app.use("/list", listRouter);
app.use("/test", testRouter);

// 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
    console.log("THERE IS AN ERROR");
    //  res.status(err.status || 500);
    // res.render("error");
});

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

// module.exports = app;

这里定义了list的路由,listRouter如下:

var express = require("express");
var router = express.Router();
var Sanguo = require("../model/db");

/* GET home page. */
router.get("/", async function (req, res) {
    // res.send("ok");
    // console.log(students);
    // return;
    var random = Math.round(Math.random() * 700);
    console.log(random);

    let results = await Sanguo.find().limit(5).skip(random).exec();

    // res.send({ students: results });
    // results.exec(function (err, results) {
    console.log(results);
    let arrayHero = [];
    for (var i = 0; i < results.length; i++) {
        // console.log("****************");

        // hero = results[i].toString();
        // console.log("hero");

        // console.log(x);
        x = JSON.parse(JSON.stringify(results[i]));
        // console.log(JSON.parse(JSON.stringify(results[i])));
        arrayHero.push(x);
        // console.log("****************");
    }
    // return;
    let heroList = arrayHero.sort(compare("wuLi", true));
    res.render("list.html", { students: arrayHero });
    // });

    // for (let index = 0; index < results.length; index++) {
    //     const element = results[index];
    //     console.log(element.name);
    // }
    // return;

    // let heros = JSON.parse(results);
    // console.log(results);
    // // res.send(results);
    // res.render("list.html", { heros: heros });
});

/** 两个参数: 参数1 是排序用的字段, 参数2 是:是否升序排序 true 为升序,false为降序*/
function compare(attr, rev) {
    // console.log(attr, rev)
    if (rev == undefined) {
        rev = 1;
    } else {
        rev = rev ? 1 : -1;
    }
    return (a, b) => {
        a = a[attr];
        b = b[attr];
        if (a < b) {
            return rev * -1;
        }
        if (a > b) {
            return rev * 1;
        }
        return 0;
    };
}

module.exports = router;

首先把三国的表引入,在model下面的db里面定义好的,然后,查询武将,

查询之前,使用random,随机生成700以内的数字,这些数字,可以作为find的参数,skip,

返回的结果,之后,把结果存入一个数组,

数组是arrayHero。这里在保存数组的过程中,要先JSON转变字符串,在用json解析,这样不会因为mongoose返回的object,第一个的_id字段无法解析。

渲染模板的过程中,还需要对武力值排序,这个是从网上搜集到的一个数组,按照某一个键排序的函数。直接抄过来的。

最后的db.js

var mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/test").then(console.log("链接陈功"));

var sanguoSchema = new mongoose.Schema({});

var Sanguo = mongoose.model("Sanguo", sanguoSchema);

module.exports = Sanguo;

ok,每次刷新页面就会随机挑出5个武将。

你可能感兴趣的:(javascript,前端,vue.js)