【问题标题】:How to send data from server to client in nodejs?如何在nodejs中将数据从服务器发送到客户端?
【发布时间】:2015-08-02 07:43:12
【问题描述】:

我在 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 给我表单输入。现在我需要将 req.body 发回给客户端,为此我在客户端(在 index.html 中)使用 ajax,如下所示:

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 {} 而不是表单输入。 我在这里错过了什么?

【问题讨论】:

  • 我认为您没有正确使用正文解析器。 github.com/expressjs/body-parser
  • 您正在发送 JSON 字符串,并且您的服务器正在转换为 JSON 对象,然后您将返回该对象 - 但不是作为字符串。试试res.json(JSON.stringify(req.body));
  • 结果是{}
  • @Vic res.json 需要一个对象,而不是 json。 :)
  • 我认为你应该使用 bodyparser 之类的 app.use(bodyParser.json({type: 'application/json'}));

标签: javascript jquery ajax node.js express


【解决方案1】:

您的代码中有两个问题:

首先,正如 cmets 所提到的,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);
        });      
})

【讨论】:

  • 也没有工作。你知道我在哪里可以找到任何明确的例子吗?
  • 它对我有用...您是在为 var 数据分配一个值,还是像您的代码示例中那样未定义? “它不起作用”是什么意思?
猜你喜欢
  • 2020-08-17
  • 1970-01-01
  • 2022-01-12
  • 2019-05-09
  • 2019-03-05
  • 2015-03-05
  • 2013-08-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多