繁体   English   中英

内联 JavaScript 和 Node.js 之间的通信

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM