我尝试在我的节点应用程序内进行通信。这意味着我添加一个登录名,然后单击一个按钮。此按钮将与服务器通信并在服务器上启动其他操作。
在这种情况下,我有一台服务器:
const express = require('express');
var bodyParser = require('body-parser');
const app = express();
app.use(express.static('public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.listen(8080, () => {
console.log('Testcafe server listening on 8080');
});
// serve the homepage
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
app.post('/clicked', (req, res) => {
console.log("Clicked aus Server");
console.log(req.body.login); //This is what I try to get here
res.sendStatus(201);
});
客户:
console.log('Client-side code running');
const button = document.getElementById('myButton');
button.addEventListener('click', function(e) {
console.log('button was clicked');
fetch('./clicked', {method: 'POST'})
.then(function(response) {
if(response.ok) {
console.log('click was recorded');
return;
}
throw new Error('Request failed.');
})
.catch(function(error) {
console.log(error);
});
});
还有一个index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" type="text/css" href="./frontend.css">
</head>
<body>
<input type="text" name="login" placeholder="Login.."><br/>
<input type="text" name="password" placeholder="Password.."><br/>
<button id="myButton">Click me!</button>
</body>
<script src="./client.js"></script>
</html>
我如何将表单数据传递给 app.post('/ clicked'函数?我尝试使用body-parser,但我想我在client.js中遗漏了一些东西。