基于node.js开发的文章生成器(八、网页版本的文章生成器--终章)

224 阅读3分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第23天,点击查看活动详情

引言

不知不觉,我们的文章生成器已经迎来了终章,这是网页版狗屁不通文章生成器的终章,也是本系列的最后一章。接下来我就带着大家完成最后这一部分的学习。

项目结构

项目目录如下

image.png

上面就是项目的目录,分别是lib文件夹,node_modules目录,resources文件夹,axios文件夹,router文件夹,和router_handle目录。

lib目录的编写

lib目录下文件如下

image.png

random.js中包含了生成随机数的randomInt()和抽象成过程的高阶函数randomFun()

article.js包含了sentence()生成句子的函数和最终的生成段落到文章的函数articleCreate()

resource目录

resource目录下包含一个data.json文件,包括我们的准备好的语料库。

router目录

这里是我们为主入口get,post请求准备的要抽象成路由的配置

router_handle目录

这里我们为router函数提供具体实现

src目录

这里我们来写项目的入口,因为之前有一个index.js文件,是控制台版的狗屁不通文章生成器代码,所以我们另外建立一个app.js作为本次项目的入口,另外我们再准备一个index.html作为本次项目的展示的页面。

index.html

这里我们写html部分的代码,代码如下:

<!DOCTYPE html>
<html>
    <head>
        <title>狗屁不通文章生成器</title>
        <style>
            body {
                background-image: linear-gradient(90deg,antiquewhite,aquamarine);
                display: flex;
            }
            h1 {
                color: coral;
                position: absolute;
            }
            .title {
                position: absolute;
                padding: 10px 10px 10px 10px;
                margin-left: 360px;
                margin-top: 120px;
                border-color: blue;
                border-top: 0px;
                border-right: 0px;
                border-left: 0px;
                border-color: brown;
                background-color:darkcyan;
                color: cornsilk;
                font-size: 20px;
            }
            .Num {
                background-color: burlywood;
                position: absolute;
                margin-left: 630px;
                margin-top: 120px;
                padding: 10px 10px 10px 10px;
                border-color: blue;
                border-top: 0px;
                border-right: 0px;
                border-left: 0px;
                font-size: 20px;
                color: cornsilk;
            }
            .Num::placeholder{
                margin-left: 15px;
                color: crimson;
            }
            .title::placeholder{
                color:cyan;
            }
            #content {
                margin-top: 185px;
                width: 80%;
                height: auto;
                margin-left: 10%;
                margin-right: 10%;
                background-color:rgb(215, 127, 64);
                flex-direction: column;
                flex-grow: 1;
                flex-basis: 630px;
                color:white;
                font-size: 18px;
            }
            .btn {
                position: absolute;
                margin-left: 960px;
                margin-top: 110px;
                padding-bottom: 23px;
                padding-right: 14px;
                border-radius: 5px;
                border-width: 6px;
                border-bottom: 6px;
                border-color: chartreuse;
                background-color: brown;
                color: aliceblue;
                font-size: 22px;
            }
            .btn:hover {
                font-size: 22px;
                background-color:coral;
                border-color: bisque;
                transition: all 1s;
                color:darkorchid;
            }
        </style>
    </head>
    <body>
        <h1>狗屁不通文章生成器</h1>
        <input id="title" class="title" name="title" type="text" placeholder="请输入文章标题" autocomplete="off">
        <input id="Num" name="Num" class="Num" type="number" placeholder="请输入字数" autocomplete="off">
        <button id="btn" class="btn">生成</button>
        <div id="content">          
        </div>
    </body>
    <script src="/axios"></script>
    <script>
        document.getElementById('btn').addEventListener('click',()=>{
            let title = document.getElementById('title').value;
            console.log(title);
            axios({
                method:"post",
                url : "http://localhost:8345/xx/create",
                data:"title="+title+"&"+"Num="+document.getElementById('Num').value,
            }).then((resp)=>{
                document.getElementById('content').innerHTML = resp.data;
            })
        },false);
    </script>
</html>

前端代码如下,背景上我用了background-image中的linear-gradient()函数做的渐变。

然后发送上我用了输入检查,控制生成的文章字数在十万字以下(主要是我穷,服务器流量没那么多...)

app.js部分代码。

准备部分

首先我们在控制台中输入npm install cors

我们下载cors来解决跨域问题。

import express from 'express';
import {readFileSync} from 'fs';
import {fileURLToPath} from 'url';
import {dirname, resolve} from 'path';
import {articleCreate} from '../lib/article.js';
import {randomInt,randomFun} from '../lib/random.js';
import cors from 'cors';

我们首先完成导入,导入express框架来使用express,导入fs模块中的readFileSync()函数来读取内容,导入path函数中的dirname和resolve函数,再导入url模块中的fileURLToPath()函数来做路径的转换,最后导入cors来解决跨域问题,再导入我们自定义的模块,包括article.js中的articleCreate()函数来完成文章的生成,random.js中的randomInt()函数和randomFun()函数。

接下来我们来配置路由。

请求的配置

我们在router目录下创建axoisSend.js和mainSend.js分别作为axios请求的响应和主要的文章生成请求的处理,同样我们也在router_handle目录中创建相应的文件作为具体函数的实现。

axiosSend.js

import {readFileSync} from 'fs';
import {fileURLToPath} from 'url';
import {dirname, resolve} from 'path';

import {generate} from '../lib/generator.js';
import {randomInt,createRandomPicker} from '../lib/random.js';
import express from 'express';
import { create } from 'domain';
const router = express.Router();
router.post('/create',(req,resp)=>
{
    const reqs = req.body;
    console.log(reqs);
    const title = reqs.title;
    let max = reqs.Num;
    console.log('执行了');
    const __dirname = dirname(fileURLToPath(import.meta.url));

    function loadCorpus(src) {
    const path = resolve(__dirname,"..", src);
    const data = readFileSync(path, {encoding: 'utf-8'});
    return JSON.parse(data);
    }

    const corpus = loadCorpus('corpus/data.json');

    const pickTitle = createRandomPicker(corpus.title);
    // const title = pickTitle();
    max = Number(max);
    console.log(typeof max);
    console.log(corpus);
    const article = generate(title, {corpus},3,max);
    console.log(`${title}\n\n    ${article.join('\n    ')}`);
    resp.send(`${title}\n\n    ${article.join('\n    ')}`)
    return `${title}\n\n    ${article.join('\n    ')}`;
});
export default router;

最后在app.js中调用,完成文章生成器的撰写、