2012-08-08 70 views
0

我有一个目标:Reciving发布对象的node.js

var val = {username:'gilbertbw',password:'password',password2:'password',email:'[email protected]',firstname:'gilbert',lastname:'BW',test:true}; 

我对它运行一些验证,然后将其张贴到我的node.js服务器:

console.log(
      $.ajax({ 
       type: 'POST', 
       url: '/signup', 
       data: val, 
       success: function(){console.log('data posted')}, 
       dataType: "json" 
      }) 
     ); 

在服务器我已经tryed刚刚调用对象VAL:

console.log(val.username); 

,并从正常后拉,就像我:

val = req.param(val,null); 
console.log(val.username); 

但是两次萤火吐出来的是500 ISE:

"{"error":{"message":"val is not defined","stack":"ReferenceError: val is not defined at exports.signup (C:\\Users\\Gilbert\\WebstormProjects\\NodeOfGames\\routes\\user.js:37:21) 

,如果我只是console.log(val);它打印空 有问题的线是当我尝试登录val.username安慰。你如何recave在node.js中发布的对象?

+0

分配'console.log'到'成功'是无效的。您将它分配给'console.log'的返回值,而不是让它执行它。你需要使用'success:function(){console.log(..); }' – 2012-08-08 17:52:57

+0

@BradChristie它记录'日志'数据发布到日志只是好的想法 – gilbertbw 2012-08-08 17:55:38

+0

你是对的,它会 - 抢先调用ajax,而不是实际上成功回调。 – 2012-08-08 17:57:39

回答

0

val是客户端变量。服务器无法知道您将该对象命名为“val”。

data: val就像是:

data: {username:'gilbertbw',password:'password',password2:'password',email:'[email protected]',firstname:'gilbert',lastname:'BW',test:true} 

所以没有val现场为您的服务器发现。

做到这一点,而不是:

data: { 
    "val": val 
} 

编辑:

也,你行req.param(val,null);应该req.param("val",null);
val = req.body.val;
reference

+0

'val'的值仍然是' null“在服务器上,有没有什么特殊的我必须做的选择'val'在服务器上? – gilbertbw 2012-08-08 18:00:05

+0

看看编辑我的答案。 – EyalAr 2012-08-08 18:17:50

+0

我仍然没有定义'val,但是使用'console.log(req.body.val)'我在服务器日志中获得预期的响应。所以'val = req.body.val'对我来说工作正常 – gilbertbw 2012-08-08 18:39:35