如何在nodejs中从服务器发送数据到客户端

How to send data from server to client in nodejs?

本文关键字:数据 客户端 服务器 nodejs      更新时间:2023-09-26

我在nodejs中运行服务器,express在文件index.html中为客户端提供html表单:

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser());
app.get('/', function(req, res){res.sendfile('index.html');});
app.post('/', function(req, res){
  res.json(req.body);
});
app.listen(8080);

req.body给出了表单输入。现在我需要发回请求。body到客户端,为了做到这一点,我在客户端使用ajax(在index.html中),像这样:

var data;
$('#submit').click(function()
{
    console.log('Button Clicked');
    $.ajax({
        url: '/',
        type:'POST',
        data: data,
        dataType: 'json',
        }).done(function(data) {
            console.log(data);
        });      
})

然而,当我点击按钮submit,我得到Object {}在浏览器控制台,而不是表单输入。我遗漏了什么?

您的代码中有两个问题:

首先,正如注释所提到的,bodyParser()已被弃用,您应该使用特定的bodyParser中间件(json、text、urlencoded、raw)。所以在你的例子中:

app.use(bodyParser.json())
第二,你的客户端调用jQuery。Ajax应该对数据进行字符串化。这样的:
$('#submit').click(function()
{
    console.log('Button Clicked');
    $.ajax({
        url: '/',
        type:'POST',
        data: JSON.stringify(data),
        dataType: 'json',
        }).done(function(data) {
            console.log(data);
        });      
})