如何通过路由器传递 html 形式的字符串以生成和存储对象?

How do I pass a string from html form, through a router in order to generate and store an object?

我试图将一个字符串从前端传递到后端,但我遇到了障碍。我正在使用 Node、Express、Body Parser、EJS 和 PostgreSQL。我的基本文件系统是这样的:

– app
   |– api
   |   |– thing.js
   |
   |– index.js

– views
   |– pages
       |– index.ejs

我在 index.ejs 中有一个表单提交将数据传递到 index.js 文件:

index.ejs

<form action="/creatething" method="post">
       <h1>Make a thing</h1>
       <p> What is your thing called?
       <input name="wtitle" type="text">
       </p>
       <p> What is your name?
       <input name="cuser" type="text">
       </p>

       <input type="submit"  value="Submit"> 
</form>

以上代码触发/creatething,放在index.js

index.js

    const express = require ('express');
    const thingRouter = require('./api/thing');
    const bodyParser = require("body-parser");
    const app = express();

    app.set('view engine', 'ejs');

    app.use(bodyParser.urlencoded({extended: false}));
    app.use('/thing', thingRouter);
    app.get('/', function (req, res){
        res.render('pages/index');
    });


    app.post('/creatething',(req,res)=>{
        console.log('clicked '+ req.body);
    });
    module.exports= app;

有了这个,我可以在控制台中创建一条消息,打印用户从表单输入的内容。但是,我试图通过 thing.js:

中的代码将此数据发送到数据库

thing.js

const {Router} = require('express');
const router = new Router();

router.get('/',(req,res)=> {
    console.log(req.body);
    // Placeholder for working code that stores thing in database :)
});

module.exports = router;

这里的问题是我不知道如何将 req.body 数据从 index.js 文件传递​​到将数据插入数据库的 thing.js 方法。我可以将数据库代码添加到 index.js 文件中,但我试图让事情更加分离并了解 routing/mounting。我现在错过了什么?

您必须更改 thing.js 文件中的一些内容。只需要几行代码,而不是从 express 导入 Router 并添加一些额外的路由。

只需复制以下代码并粘贴到您各自的文件中。

thing.js

const get = (req, res) => {
    console.log(req.body);
}

module.exports = get;

index.js

const express = require ('express');
const get = require('./api/things');
const bodyParser = require("body-parser");
const app = express();

app.set('view engine', 'ejs');

app.use(bodyParser.urlencoded({extended: false}));
app.get('/', function (req, res){
    res.render('pages/index');
});


app.post('/creatething', (req,res)=>{
    get(req,res);
});
app.listen(4000, () => {
    console.log('App is running on port: 4000');
});
module.exports= app;

希望这能帮助您解决问题。