【问题标题】:I'm having trouble with Node.js handling post requests我在使用 Node.js 处理发布请求时遇到问题
【发布时间】:2020-03-24 10:14:18
【问题描述】:

我想使用 Node.js 处理来自网页的表单数据,然后将数据写入文件。 目前,我在 Node.js 无法正确处理我的 POST 请求时遇到一些问题,或者我可能没有正确地从网页发送请求。

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
...    
</head>
<body>
    <main class="content">
        <form action='/build' method='POST'>
            <section>
                <h3> Personal information </h3><br>
                <label for="fullName">What is your (full) name?</label><br>
                <input type="text" name="fullName" id="fullName"><br>
                <label for="address">What is your address?</label><br>
                <input type="text" name="address" id="address"><br>
                <label for="e-mail" >What is your e-mail</label><br>
                <input type="text" name="e-mail" id="e-mail" onkeyup='checkEmail()'><br>
                <label for="phonenr">What is your phone number?</label><br>
                <input type="text" name="phonenr" id="phonenr" onkeyup='checkPhone()'><br>
        </section>
        <hr>
        <section>
                <h3> Work experience </h3> <br>
                <ul id='xpul'>
                    <li>
                        <label for="xp1-title">Title</label> <br>
                        <input type='text' name='xp1-title' id='xp1-title'> <br>
                        <label for='xp1-desc'> Description of your job </label> <br> 
                        <textarea name='xp1-desc' id='xp1-desc' placeholder="What did you do? What did you learn? What skills did you gain?"></textarea> <br>
                    </li>
                </ul>
                <button class='add-button' type='button' onclick='addExperience();'>Add Experience</button>

        </section>
        <hr>
        <section>
                <h3> Education </h3> <br>
                <ul id='edul'>
                    <li>
                        <label for='ed1-title'>Title</label> <br>
                        <input type='text' name='ed1-title' id='ed1-title'> <br>
                        <label for='ed1-desc'> Description of your education </label> <br> 
                        <textarea name='ed1-desc' id='ed1-desc' placeholder='What did you do? What did you learn? What skills did you gain?'></textarea> <br>
                    </li>
                </ul>
                <button class='add-button' type='button' onclick='addEducation();'>Add Education</button>
        </section>
        <hr>
        <section>
                <h3> Skills </h3> <br>
                <ul id='skill'>
                    <li>
                        <label for='sk1-title'>Title</label> <br>
                        <input type='text' name='sk1-title' id='sk1-title'> <br>
                        <label for='sk1-desc'> Description of your Skill </label> <br> 
                        <textarea name='sk1-desc' id='sk1-desc' placeholder='How did you gain this skill? Why is it important? Etc.'></textarea> <br>
                    </li>
                </ul>
                <button class='add-button' type='button' onclick='addSkill();'>Add Skill</button>

        </section>
        <input type='submit' value='Build your resume!' class='build-button'>
    </form>

    </main>
    <script src="js/scripts.js"></script>
</body>
</html>

app.js(节点):

// I use fs because I want to write data from an object to a file.
const fs = require('fs');
// Querystring for beautifying the object data, I think.
const qs = require('querystring');

const express = require('express')
const app = express()
const port = 3000
app.use('/css', express.static('./css'));
app.use('/js', express.static('./js'));
app.use('/img', express.static('./img'));

// I just saw this on StackOverflow. I don't even know why I need it. But I'm getting desperate and I feel stressed the hell out. Help me for god's sake.
app.use(express.urlencoded());
app.use(express.json());

// Home page
app.get('/', function(req,res){

    res.sendFile(__dirname+"/index.html");
});

// app.route('/build') is where I start listening for the POST request. The HTML form has /build as its action, with method 'POST'.
app.route('/build')
.post(function(req,res){
    var body = [];

    req.on('data', function (data) {
        body.push(data)
    });

    req.on('end', function () {
        var post = qs.parse(body);
        console.log(post['fullName']);

    });
    console.log(body);
    console.log(req.body.person);

    res.send("Yo we got the message");

})

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

输出:

[] // A.N.: This is the console.log(body);
TypeError: Cannot read property 'fullName' of undefined
    at D:\xampp\htdocs\ResumeBuilder\app.js:41:33
    at Layer.handle [as handle_request] (D:\xampp\htdocs\ResumeBuilder\node_modules\express\lib\router\layer.js:95:5)
    at next (D:\xampp\htdocs\ResumeBuilder\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (D:\xampp\htdocs\ResumeBuilder\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (D:\xampp\htdocs\ResumeBuilder\node_modules\express\lib\router\layer.js:95:5)
    at D:\xampp\htdocs\ResumeBuilder\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (D:\xampp\htdocs\ResumeBuilder\node_modules\express\lib\router\index.js:335:12)
    at next (D:\xampp\htdocs\ResumeBuilder\node_modules\express\lib\router\index.js:275:10)
    at jsonParser (D:\xampp\htdocs\ResumeBuilder\node_modules\body-parser\lib\types\json.js:101:7)
    at Layer.handle [as handle_request] (D:\xampp\htdocs\ResumeBuilder\node_modules\express\lib\router\layer.js:95:5)

您可能会说,我对 NodeJS 或请求的经验很少。

【问题讨论】:

  • 您的body 显示为空,因为它在发送任何数据之前正在打印。如果您在end 上打印,您会看到其他内容。如果你只使用某些express middleware 来解析正文会更容易

标签: javascript node.js express


【解决方案1】:

发布请求不需要查询字符串(至少在您的情况下)。

另外,req.on('data'), req.on('end') 在这里是多余的。

试试这个:

app.route('/build')
    .post(function (req, res) {
        var post = req.body;
        console.log(post['fullName']);
        res.send("Yo we got the message");
    });

【讨论】:

  • 对于任何正文内容 AFAIK,您仍然需要解析器。 Express 文档没有列出正文的任何​​默认解析。
【解决方案2】:
  • 您不需要 json 正文解析器 (express.json),因为请求负载不是 JSON 格式。

  • 1234563

考虑到这一点,您可能需要如下调整 Node.js 代码:

const express = require('express')
const app = express()
const port = 3000
app.use('/css', express.static('./css'));
app.use('/js', express.static('./js'));
app.use('/img', express.static('./img'));

app.use(express.urlencoded());

// Home page
app.get('/', function(req,res){
  res.sendFile(__dirname+"/index.html");
});

app.route('/build')
  .post(function(req,res) {
    console.log(req.body); // req.body contains the form values
    res.send('Yo we got the message, ' + req.body.fullName);
  })

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-02
    • 2023-02-13
    • 1970-01-01
    • 2019-11-19
    • 1970-01-01
    • 2020-02-08
    相关资源
    最近更新 更多