【问题标题】:Express POST request body outputting unidentified and {}Express POST 请求正文输出身份不明和{}
【发布时间】:2022-01-17 03:38:42
【问题描述】:

我很难从 HTML 表单中检索快速发布请求的正文。在我的代码中,我尝试使用 JSON.stringify 提取它通常是原始的。仍然没有骰子,只是输出:""Body: "undefined" 在 app.js 中收到! -------- 正文:“[object Object]”在 app.js 中收到!“”控制台输出 undefined 和 {}。任何帮助表示赞赏。 Bellow 是我的 JS 代码和 HTML 代码。

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

const path = require('path');

const bodyParser = require('body-parser'); 
app.use(bodyParser.json()); 

app.use(express.urlencoded({
    extended: true
  }))

app.get('/', function(req, res) {
    res.sendFile(path.join(__dirname, './index.html'));
})

app.post('/submit-form', function(req, res) {

    var x = req.body.key;
    var y = req.body;

    console.log(x);
    console.log(y);

    console.log(JSON.stringify(x));
    console.log(JSON.stringify(y));
    
    res.send(`Body: "${x}" recieved in app.js! ------- Body: "${y}" recieved in app.js!`);

})

app.listen(4001, function() {
    console.log("Server is listening on port 4001...");
})
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Sample Site</title>

  <style>
    body { padding-top: 50px; }
  </style>
</head>
<body>

  <div class="container">
    <div class="jumbotron">
      <h1>res.sendFile() Works!</h1>
      
      <form method="POST" action="/submit-form", body= "key: 'hellow wolrd'"}>
        <input type="submit">
      </form>

    </div>
  </div>

</body>
</html>```

【问题讨论】:

    标签: javascript html node.js post


    【解决方案1】:

    POST 请求的主体由表单中命名的表单控件(inputselect 等元素)的值确定。

    &lt;form&gt; 元素没有 body 属性。

    MDN has a forms + express tutorial,我建议你阅读。

     <form method="POST" action="/submit-form">
         <input name=key value="hello, world">
         <button>Submit</button>
     </form>
    

    【讨论】:

    • 谢谢,刚刚测试过,这行得通。我注意到如果我删除 行,文本框就会消失。无论如何我可以删除文本框但仍然让提交按钮传递我定义的静态值。例如,我正在制作一个石头剪刀布游戏,我希望每个选项都有一个按钮。
    • @AdamSpera 您可以尝试将type='hidden' 添加到输入元素。
    • 给每个提交按钮一个名称和值。不要使用隐藏的输入。
    猜你喜欢
    • 2023-04-10
    • 1970-01-01
    • 2019-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多