【问题标题】:Arrays in EJS returning undefined and null value in NodeJS - ExpressEJS 中的数组在 NodeJS 中返回未定义和空值 - Express
【发布时间】:2020-11-22 21:49:52
【问题描述】:

这是我的 ejs 代码

<% var 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>

这是我的 controller.js 代码

control.post('/like', (req, res, next) => {
    let tags = [req.body.likes];
    console.log(tags);
    iglike(tags);
    next();
    res.send(tags);
     
});

当我从name = "likes[]" 中删除[] 时,代码会完美地返回输入的数据。

但在name = "likes[]" 上,代码在控制台日志中返回undefined

例如: 点赞[]

Input : App, Web

Output: [null] , In Console: Undefined

没有喜欢[]

Input: app, web
Output: ['app, web'] ( Stores them into single array)

我希望我的输出是

Input: app, example, thanks
Output: ['app','example','thanks']

我正在使用 EJS 视图引擎和 node-express 我也在我的 app.js 中添加了app.use(express.urlencoded({extended: false})) 代码。

【问题讨论】:

  • tag 是字符串数组而不是对象数组,likes 不会被定义,将&lt;%= tag[i].likes %&gt; 更改为&lt;%= tag[i] %&gt;
  • 我试过了,还是一样。
  • 我认为需要extended: true才能将数组与body-parser一起使用。

标签: javascript node.js arrays express ejs


【解决方案1】:

更改扩展为 true:

app.use(express.urlencoded({extended: true}))

并从 req.body.likes 中删除方括号:

let tags = req.body.likes;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-28
    • 2016-05-20
    • 2021-01-28
    • 2020-08-17
    • 2020-09-16
    • 1970-01-01
    • 2014-07-20
    • 2021-06-02
    相关资源
    最近更新 更多