我在处理发布请求的Node.js遇到麻烦

时间:2019-11-28 17:55:45

标签: javascript node.js express

我想使用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或请求的了解很少。

2 个答案:

答案 0 :(得分:0)

对于发帖请求,您不需要查询字符串(至少在您的情况下如此)。

此外,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");
    });

答案 1 :(得分:0)

  • 您不需要JSON主体解析器(express.json),因为请求有效负载不是JSON格式。

  • 由于您使用express.urlencoded中间件,因此您无需在变量中手动缓冲请求主体并对其进行解析,则中间件将为您完成请求(并将已解析的有效负载保存在{{1 }}。

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

req.body