【发布时间】: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