【问题标题】:Send Data which I get from EJS to my other NodeJs Script (NodeJs express)将我从 EJS 获得的数据发送到我的其他 Node Js 脚本(Node Js express)
【发布时间】:2020-08-02 22:19:18
【问题描述】:

这是我的 Index.js 文件

const ig = require('./like');

const iglike = async() => {

   await ig.initialize();

   await ig.login('example', 'examplepass');

   await ig.liketagsprocess(***tags***);

   debugger;

};

module.exports = iglike;

这是我的 controller.js(路由)

control.get('/like', (req, res) => {
    res.render("like");
    
});

control.post('/like', (req, res, next) => {
     let tags = req.body.likes;
     console.log(tags);
     const likeobj = require('./bin/index')(like);
     res.send(likeobj.iglike);
     next();
     res.send(tags);
     
});

这是我获取数据的表单 [EJS]

<% (tag = ['']) %>
<form action="/like" method="POST">
    <% for (var i in tag){%>
        Tag: <input type="text" name="likes" value="<%= tag[i].likes %>"/><br><br>
        <button type="submit" value="accept">Send Tag</button><br><br><hr>
    <%} %>
</form>

我是一名高中生,正在使用 Node express 制作我的第一个 Web 应用程序。抱歉解释不好。

我需要做的是让表单接受来自用户的数组并将其发送到“标签”下的 Index.js。

使用此代码,我只能接受一个字符串并在控制台中打印它。

当我去 localhost/like 时

表单显示并在输入数据后在控制台中打印并在 index.js

中执行我的代码

我无法将控制台中打印的数据传递给我的 index.js 文件。

我收到此错误

(node:7140) UnhandledPromiseRejectionWarning: ReferenceError: tags is not defined

感谢您的帮助!

【问题讨论】:

    标签: javascript node.js express post ejs


    【解决方案1】:

    您需要更改一些内容:

    在您的 index.js 文件中,为您的函数添加一个参数:

    const ig = require('./like');
    
    const iglike = async (tags) => { // < here
    
      await ig.initialize();
    
      await ig.login('example', 'examplepass');
    
      await ig.liketagsprocess(tags);
    
      debugger;
    
    };
    
    module.exports = iglike;
    

    在你的 controller.js 中,你可以在文件顶部导入你的 iglike 函数,并在你的路由中使用它,将标签作为参数传递:

    const iglike = require('./bin/index');
    
    control.get('/like', (req, res) => {
      res.render("like");
    });
    
    control.post('/like', (req, res, next) => {
      let tags = req.body.likes;
      console.log(tags);
      iglike(tags);
      next();
      res.send(tags);
    });
    

    在您的 ejs 文件中,您应该将输入的名称更改为 likes[],以便它可以是一个数组:

    <% (tag = ['']) %>
    <form action="/like" method="POST">
        <% for (var i in tag){%>
            Tag: <input type="text" name="likes[]" value="<%= tag[i].likes %>"/><br><br>
            <button type="submit" value="accept">Send Tag</button><br><br><hr>
        <%} %>
    </form>
    

    【讨论】:

    • 谢谢!它现在工作正常,但我面临另一个问题。在我的 ejs 文件中,当我输入 likes[] 并输入数据假设——应用程序、节点——控制台显示未定义。
    • 你在使用 body-parser 包吗?如果没有,你需要在 express 中解析 body,在这里查看 express/connect 顶级通用示例:expressjs.com/en/resources/middleware/body-parser.html You need to parse application/x-www-form-urlencoded
    • 再次感谢您!我尝试添加 body-parser 还是一样,请查看我提供的问题的最新问题。
    猜你喜欢
    • 2013-12-16
    • 2018-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-31
    • 2019-01-29
    • 2021-07-02
    相关资源
    最近更新 更多