【问题标题】:EXPRESS: express.urlencoded IS NOT WORKING快递:express.urlencoded 不工作
【发布时间】:2021-07-08 16:29:12
【问题描述】:

如果有人能解释原因,我不知道为什么 console.log(req.body) 没有显示任何输出 当我填写详细信息并提交时,req.body 应该在终端中打印详细信息,但它什么也不显示 我是nodejs的新手,还请解释为什么实际上它没有打印输出

代码:

const express = require('express');
const path = require('path');
const app = express();

//express related stuff
app.use('/static',express.static('static'));
app.use(express.urlencoded());

//pug specific stuff 
app.set('view engine', 'pug');
app.set('views',path.join(__dirname,'views'));

//endpoint

app.get('/',(req,res)=>{
    const con = "knowledge";
    const parans = {'title':'PUBG','content': con};
    res.status(200).render('index.pug',parans);
});
app.post('/',(req,res)=>{
    console.log(req.body);
    const parans = {'message': 'your form has been submitted'};
    res.status(200).render('index.pug',parans);
})

//listen,port
app.listen(80,()=>{
    console.log("sucess on port 80");
});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>#{title}</title>
    style
        include ../static/style.css
</head>
<body>
    <nav>
        <ul>
            <li><a href="/">HOME</a></li>
            <li><a href="/about">ABOUT</a></li>
            <li><a href="/joinus">JOIN_US</a></li>
        </ul>
    </nav>
    <h1>HEADING</h1>
    <!--<h2>#{content}</h2>
    <p>this is plain HTML using PUG</p>-->
    <div class="container">
        <form action="/" id="contact">
            <input type="text" id="name" placeholder="ENTER YOUR NAME">
            <input type="text" id="AGE" placeholder="ENTER YOUR AGE">
            <input type="text" id="GENDER" placeholder="ENTER YOUR GENDER">
            <button class="btn">Submit</button>
        </form>
    </div> 
</body>
</html>

【问题讨论】:

  • 您是否希望您为路由app.post('/', …) 设置的编码在这里触发?没有理由发生这种情况 - 您的 form 元素没有明确设置 method,因此将使用默认的表单提交方法 GET

标签: javascript node.js pug backend


【解决方案1】:

express.urlencoded() 无法解析那些缺少name 属性的输入字段。

要解决这个问题,只需在&lt;form&gt;内的每个输入标签中添加HTML名称属性即可。

示例:

 <input name='name' type='text'>
 <input name='age' type='number'>
        ^^^^^^^^^^

【讨论】:

    【解决方案2】:

    首先安装 npm install body-parser 然后添加这些行

    Code:
     const bodyParser=require("body-parser");
     app.use(bodyParser.json());
     app.use(express.urlencoded({ extnded: true }));
    

    【讨论】:

    • 从客户端发送数据或空json.check正确
    • 让 headers = new Headers(); headers.append('content-type','application/json'); fetch('/', { method: 'POST', headers: headers, body: JSON.stringify(form_data) }).then(function (response) { console.log("response.."); return response.json (); }).then(function (user_json) { console.log(user_json); });
    猜你喜欢
    • 2017-09-19
    • 1970-01-01
    • 2018-11-22
    • 2015-10-24
    • 1970-01-01
    • 1970-01-01
    • 2018-06-03
    • 1970-01-01
    • 2022-01-25
    相关资源
    最近更新 更多