【问题标题】:cannot access the POST form data sent by HTML/Javascript code at node js code无法访问节点 js 代码中 HTML/Javascript 代码发送的 POST 表单数据
【发布时间】:2021-06-24 19:31:57
【问题描述】:

我制作了一个简单的 nodejs 服务器,它为用户提供一个 html 页面。该页面包含一个用户 ID 的输入文本框。当用户按下按钮提交时,我将用户输入的用户 ID 放入表单数据中,并通过 POST 方法将其发送到我的服务器函数(submitForTest)。

现在,在处理 submitForTest 的 nodejs 函数中,我尝试访问 userID ,但我将 res.body 作为 {} 获取,因此无法弄清楚如何在此处访问 userID。

谁能指出我需要在我的节点 js 代码中获取用户 ID。

我的 HTML 文件:

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
  <div>
   <label>User ID</label>
    <div>
      <input type="text" id="userid" >
    </div>
  </div>

  <div>
    <div>
      <button type="submit" onclick="submitForTest()">Submit</button>
    </div>
  </div>

    <script type="text/javascript">

        function submitForTest()
        {
            var userID = document.getElementById('userid').value;
      let formData = new FormData();
            formData.append("userID", userID);

        //alert("hello");
            fetch('http://MY-SERVER:3000/submitForTest', {method: "POST", body: formData});
        }

        </script>
  </body>
</html>

我的节点 js 文件:

'use strict'
const fs = require("fs")
const express = require('express')
var path = require('path')

const app = express()
var bodyParser = require('body-parser')
app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
}));

var jsonParser = bodyParser.json();

app.get('/',function(req,res) {
  res.sendFile('small.html');
});

app.post('/submitForTest', function(req, res) {
//want to print userID here .. but the below is coming as {} here ..
 console.log(req.body);

})

// Tell our app to listen on port 3000
app.listen(3000, function (err) {
  if (err) {
    throw err;
}
  console.log('Server started on port 3000')
})

请帮忙。

问候

【问题讨论】:

  • 您尝试了吗 - app.post('/submitForTest', function(req, res) => { ? 将结果传递给匿名函数。
  • 抱歉无法关注您的评论,能否请您提供更多详细信息。我对node js 编程非常陌生
  • 尝试在 (req,res) 和括号之间添加 =>。看起来像一个输入函数而不是结果处理程序
  • router.get('/handle',(request,response) => { //执行特定操作的代码。 //要访问 GET 变量,请使用 req.query() 和 req.params( ) 方法。});
  • 仍然得到 {} : app.post('/submitForTest', (req, res) => { console.log(req.body); console.log(req.params); })

标签: javascript html node.js


【解决方案1】:

问题是FormData 正在发送编码为multipart/form-data 的正文。您必须添加能够处理 multipart 正文格式的中间件。例如Busboymulter

使用multer上传文件并发送userID字段的示例:

// --- form
<form action="/submitForTest" enctype="multipart/form-data" method="post">
    <input type="file" name="uploaded_file">
    <input type="text" name="userID">
    <input type="submit" value="Submit">            
</form>
// --- server
var multer  = require('multer')
var upload = multer({ dest: './uploads/' }) // where the uploaded files will be stored
app.post('/submitForTest', upload.single('uploaded_file'), function (req, res) {
   // req.file is the name of your file in the form above, here 'uploaded_file'
   // req.body will hold the text fields, if there were any 
   console.log(req.file, req.body)
});

或者以urlencodedjson 格式发送您的数据。类似json 的东西,例如:

function submitForTest()
{
    var userID = document.getElementById('userid').value;
    fetch('http://MY-SERVER:3000/submitForTest', {
        method: "POST",
        headers: {
            'Content-type': 'application/json',
        },
        body: JSON.stringify({ userID }),
    });
}

【讨论】:

  • 你能举个例子来解决这个问题吗?
  • 或者请告诉我如何以 json 格式发送我的数据?
  • 我假设您没有将二进制数据发送到服务器以使用json。这样就容易多了。
  • 实际上我还会在表格中发送更多内容。像更多的文本字段和一些对象(通过上传文件窗口框传递的对象)。那么你能告诉你如何在你提供的答案中给出这个答案吗?
  • 好吧,对于二进制数据(作为文件),最好使用FormData 对象。然后只需将multipart 正文解析器之一添加到中间件链。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-09
  • 1970-01-01
  • 2012-08-21
  • 1970-01-01
  • 1970-01-01
  • 2015-01-10
  • 1970-01-01
相关资源
最近更新 更多