"真" $ .post发送的值未在后端考虑

时间:2014-11-10 20:21:31

标签: javascript jquery node.js express

我在处理真/假/空值的问题上摸不着头脑,我尝试了几种变体,包括类型强制,假,零等。

基本上,当我点击某人的个人资料图片时,会发生在前端:

var isProfilePhoto = false;

if ( $(this).data('profilephoto') === true ) {
  isProfilePhoto = true;
  photoId = parseInt( $(that).data('photoid') );
}

$.post('/mod', { isProfilePhoto: isProfilePhoto, photoId: photoId },
  function (data) {
    if (data.msg === 'delete pic success') {
      $(that).css({ opacity: 0 });
    } else {
      alert("There was a problem. Please contact the webmaster. ERROR CODE: " + data.msg);
    }
});

在后端,我有一个if / else案例,检查它的个人资料照片,if如下:

  console.log(req.body.isProfilePhoto); // true
  if (req.body.isProfilePhoto == true) {
    ModModel.deletePhoto(photoId, function () {
      if (userIp !== null) {
        ModModel.banUserIP(userIp, function (response) { if (response === true) { return res.send('delete pic success') } } );
      } else {
        return res.send({msg: 'delete pic success'});
      }
    });
  } else {
    // other stuff
  }

然而,一旦在后端进入其他情况,即使req.body.isProfilePhoto为真,也会转到其他情况......

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

您的代码将使用Content-Type application/x-www-form-urlencoded和POST主体发出POST请求,如下所示:

isProfilePhoto=true&photoId=123

你的服务器接收它作为一个字符串(好吧,一个字节流......),除非你有代码或一些模块告诉它,否则它无法知道四个字节true应该是转换为布尔值,或者三个字节123应该转换为数字(尽管你的ORM很可能在某个时候处理后者)。

解决此问题的一种方法是发送JSON请求。 (在jQuery中,您通过将"json"作为第4个参数传递给$.post来完成此操作。在这样的请求中,Content-Type将是application/json,POST主体看起来像这样(除了没有空格):

{ "isProfilePhoto": true,
  "photoId":        123 }

在JSON中,true始终是一个布尔值,"true"始终是一个字符串,因此当您的服务器解析它时,它将自动拥有正确的类型。当然,您必须更改服务器端代码以解析JSON正文,但这些日子非常简单。