[英]Communication between inline JavaScript and Node.js
我正在使用 Node.js,我想在按下按鈕時向服務器發送一個包含輸入值的請求。
所以這是我的 HTML 代碼:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<input id="input" action="/onclick" autocomplete="off">
<button id="button">Send</button>
<script>
let input = document.getElementById('input');
document.getElementById('button').addEventListener('click', (event) => {
event.preventDefault();
let value = input.value;
if (value) {
let data = {};
data.title = 'getValue',
data.message = value;
$.ajax({
url:'/onclick',
data: JSON.stringify(data),
type: 'POST',
success: (responseData) => {
console.log('Success!');
},
});
input.value = null;
}
});
</script>
</body>
</html>
這是我的 server.js :
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
app.post('/onclick', (req, res) => {
console.log('body: '+ JSON.stringify(req.message));
res.send(req.message);
});
server.listen(3000, () => {
console.log('listening on *:3000');
});
該代碼不會引發任何錯誤(它在瀏覽器控制台中返回Success!
),但問題是在 Node.js shell 中它發送body: undefined
而不是輸入值。
你知道怎么解決嗎?
提前致謝,
在 server.js 中添加此行以訪問請求正文:
app.use(express.json());
並使用req.body
而不是req.message
來訪問請求正文
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.