简体   繁体   English

带有 Express 的 Node.js:req.body 未定义

[英]Node.js with Express: req.body is undefined

I met the problem that the req.body of my Node.js always got undefined or NULL.我遇到了我的 Node.js 的 req.body 总是 undefined 或 NULL 的问题。

I found many past post.我发现很多过去的帖子。 Some mentioned about the need of post-method, the body-parser and the need of property name of the tag.有人提到需要post-method、body-parser以及需要标签的属性名。 But not working for me at all.但根本不适合我。 All I've added in my code.我在代码中添加的所有内容。

server.js服务器.js

const port = "5411";
const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const bcrypt = require('bcrypt');
const app = express()

app.listen(port, function () {
  console.log("server is running on " + port);
});
app.use('/static', express.static("static"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

const db_con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "mitac123",
  database: "human_resource"
});

db_con.connect(function (err) {
  if (err) throw err;
  console.log("DB Connected!");
});

app.get("/upload", function (req, res) {
  res.sendFile(__dirname + "/html/homework.html");
});

app.post("/upload", function (req, res) {
  let name = req.body.name;           //it's here that I use console.log that get NULL or undefined
  let username = req.body.username;
  let password = req.body.password;
  let gender = req.body.gender;
  let email = req.body.email;
  let question = req.body.securityQ;
  let answer = req.body.answer;
  DB_CreateOrUpdate(res, name, username, password, gender, email, question, answer);
})

function DB_CreateOrUpdate(res, name, username, password, gender, email, question, answer){
  saltRounds = 10;
  data = {
    realName: String(name), 
    username: String(username),
    password: bcrypt.hash(password, saltRounds),
    gender: gender,
    email: String(email),
    securityQ: question,
    answer: answer,
  }
  var sql_com = "INSERT INTO user_data SET ?"
  
  db_con.query(sql_com, data, function (err, result) {
    if (err) throw err;
    console.log("1 record inserted");
    console.log(result);
    return res.send("Add successful!");
  })
};


HTML file HTML文件

<!DOCTYPE html>
<html lang="zh-Hant-TW">

<head>
    <meta charset="utf-8">
    <meta name="author" content="JustBelieveMe">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="../static/js/homework.js" type="text/javascript"></script>
    <script src="http://static.runoob.com/assets/jquery-validation-1.14.0/lib/jquery.js"></script>
    <script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>
    <script src="https://static.runoob.com/assets/jquery-validation-1.14.0/dist/localization/messages_zh.js"></script>
    <link rel="stylesheet" href="../static/css/homework.css" type="text/css" />
</head>

<body>
    <header name="header" id="header">
        Account Register Page
    </header>
    <div name="basicData">
        <form name="sheet" id="sheet" ref="fileUpload" action="/upload" method="POST" enctype="multipart/form-data">
            <fieldset>
                <legend>基本資料</legend>
                <br>
                真實姓名:<input type="text" name="name" id="name">
                <br>
                使用者帳戶:
                <input type="text" name="username" id="username">
                <br>
                密碼:
                <input type="password" name="password" id="password">
                <br>
                請再輸入一次密碼:
                <input type="password" name="verifyPassword" id="verifyPassword">
                <br>
                性別:
                <select name="gender" id="gender">
                    <option value="0">男</option>
                    <option value="1">女</option>
                </select>
                <br>
                大頭貼:
                <input type="file" name="headShot" id="headShot" value="選擇檔案" accept="image/gif, image/jpeg, image/png">
                <img id="imgPreview" style="width: 200px;" src="#" />
                <br>
                Email:
                <input type="email" name="email" id="email">
                <br>
                安全問題:
                <select name="securityQ" id="securityQ">
                    <option value="0">最喜歡吃的食物?</option>
                    <option value="1">第一隻養的寵物名字?</option>
                    <option value="2">最常用的網路ID?</option>
                    <option value="3">就讀哪一所國中?</option>
                    <option value="4">幾歲時拿到第一台個人電腦?</option>
                </select>
                <br>
                安全問題答案:
                <input type="text" name="answer" id="answer">
            </fieldset>
            <div name="buttonArea" id="buttonArea">
                <input type="submit" class="buttonC" id="submit" value="送出">
                <input type="button" class="buttonC" id="clear_btn" value="清除">
                <input type="button" class="buttonC" value="填值">
            </div>

    </div>
    </form>
    <footer name="footer" id="footer">
        <div>
            copyright© 2020 JustBelieveMe All Rights Reserverd.
        </div>
    </footer>
</body>

</html>

By the way, I will got an error:顺便说一句,我会得到一个错误:

UnhandledPromiseRejectionWarning: Error: data and salt arguments required

but I think it is caused by the null value of the req.body that the hash doesn't work.但我认为这是由 req.body 的空值引起的,散列不起作用。

Well try this out:试试这个:

install multer npm i multer安装multer npm i multer

var multer  = require('multer')
var upload = multer({ dest: 'uploads/' })


app.post('/upload', upload.single('headShot'), function (req, res, next) {
  console.log(req.file);
  console.log(req.body);
})

Also as i see you are trying to do database operation.此外,正如我所看到的,您正在尝试进行数据库操作。 Should'nt it be asyncronous?不应该是异步的吗? May affect your situation maybe.可能会影响你的情况。

app.post("/upload", async function (req, res) {
      // your code goes
      // then
      await yourAsyncDBOperationFunction(req.body);
});

Also dont forget to use bodyParser.也不要忘记使用bodyParser。 If u use for example express, then use the bodyParser as a middleware in your script file (app.js/index.js/server.js)如果你使用例如 express,那么在你的脚本文件 (app.js/index.js/server.js) 中使用 bodyParser 作为中间件

Look this: https://github.com/expressjs/body-parser看这个: https : //github.com/expressjs/body-parser

Finally, I found the way to solving it.最后,我找到了解决它的方法。

I use我用

const fileUpload = require('express-fileupload'); 

...
app.use(fileUpload());

And the problem solved.问题解决了。

I guess multer is likely and I tried again.我猜multer很可能,我又试了一次。 Finally got the same answer.终于得到了同样的答案。

const multer  = require('multer');
const upload = multer({ dest: 'uploads/' });

...
app.post("/upload", upload.single('headShot'), async function (req, res) {
...
}

So I am here offer another solution.所以我在这里提供另一种解决方案。 Also thanks everyone here.在此也谢谢大家。

And could anyone tell me what difference between express-fileupload and multer ?谁能告诉我express-fileuploadmulter之间有什么区别?

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

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