【发布时间】: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