[英]NodeJS req.body JSON there but no value
index.js: index.js:
var express = require('express');
var server = express();
var bodyParser = require('body-parser');
server.use(express.static('public'));
server.use(bodyParser.json());
server.post('/saveentry', (req, res) => {
console.log(req.body);
res.send("Eintrag gespeichert");
});
server.listen(80, 'localhost');
index.html: index.html的:
<html>
<head>
<title>Gästebuch</title>
</head>
<body>
<div id="guestbook"></div>
<input type="text" id="entry" name="entry">
<button id="submit">Senden</button>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script>
var formData = {
entry: $("#entry").val()
}
$('#submit').click(function()
{
$.ajax({
type: 'POST',
url: '/saveentry',
data: JSON.stringify(formData),
dataType: "text",
contentType : "application/json",
success: function (data) {
console.log(data);
}
});
});
</script>
</body>
</html>
This is the result in the console if I press "Senden": { entry: '' } 如果按“ Senden”,这是控制台中的结果:{entry:''}
How can I get the text entered in the form? 如何获得在表格中输入的文字? What else can I try?
我还能尝试什么? I didn't find the solution online.
我没有在线找到解决方案。
You should receive value from input inside callback function: 您应该从回调函数内的输入接收值:
$('#submit').click(function() {
var formData = {
entry: $("#entry").val()
};
$.ajax({
type: 'POST',
url: '/saveentry',
data: JSON.stringify(formData),
dataType: "text",
contentType : "application/json",
success: function (data) {
console.log(data);
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.