简体   繁体   English

我在 Node.js 处理发布请求时遇到问题

[英]I'm having trouble with Node.js handling post requests

I want to handle form data from a webpage using Node.js, then write the data to a file.我想使用 Node.js 处理来自网页的表单数据,然后将数据写入文件。 Currently, I'm having a bit of an issue with Node.js not handling my POST request correctly, or perhaps I'm not sending the request from the webpage correctly.目前,我遇到了 Node.js 没有正确处理我的 POST 请求的一些问题,或者我没有正确地从网页发送请求。

HTML: 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 (node): 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}!`))

Output:输出:

[] // 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)

As you might be able to tell, I have very little experience with NodeJS, or requests.您可能会说,我对 NodeJS 或请求的经验很少。

You don't need querystring for post requests (at least at your case).您不需要发布请求的查询字符串(至少在您的情况下)。

Also, the req.on('data'), req.on('end') are redundant here.此外,req.on('data'), req.on('end') 在这里是多余的。

Try this:尝试这个:

app.route('/build')
    .post(function (req, res) {
        var post = req.body;
        console.log(post['fullName']);
        res.send("Yo we got the message");
    });
  • You don't need json body parser ( express.json ) since the request payload is not in JSON format.您不需要 json 正文解析器 ( express.json ),因为请求负载不是 JSON 格式。

  • Since you use express.urlencoded middleware, you don't need to manually buffer the request body in a variable and parse it, the middleware does it for you (and saves the parsed payload in req.body ).由于您使用express.urlencoded中间件,因此您无需手动将请求正文缓冲在变量中并对其进行解析,中间件会为您完成(并将解析的有效负载保存在req.body )。

Taking this into account you may want to adjust your Node.js code as follows:考虑到这一点,您可能需要按如下方式调整 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}!`))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM