如何解析响应[对象对象]

时间:2017-04-03 18:28:46

标签: javascript node.js express

请求是从href=url的onclick发送的。当这个网址被命中时,我将数据从服务器返回到客户端作为查询字符串。

res.redirect("/#blog_post_details/?dataUrl="+response[0].attributes);

当我使用打印时:

var posts = DataMixin.getParameterByName(dataUrl);
console.log('posts', posts); //I get [Object, Object]

我也试过JSON.Stringifyconsole.log('posts', JSON.Stringify(posts)); 使用引号"[Object,Object]"

打印相同的内容

返回查询字符串的函数:

getParameterByName: function (name, url) {
    if (!url) {
      url = window.location.href;
    }
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

但是,我能够在服务器上打印响应数据:

{ created_at: '4/3/2017, 1:23:28 AM',
  details: 'jjj',
  id: 136,
  post_id: '1491162808010',
  title: 'Basic Syntax and Tag declaration',
  url: 'basic_syntax_and_tag_declaration',
  userImage: 'assets/img/spiritual-icon4.png',
  username: 'k999@gmail.com' }

注意:我正在使用带有nodejs的expressjs

1 个答案:

答案 0 :(得分:4)

[Object, Object]发送的值。解析它不会有任何好处,解析没什么用。

您需要确定发送数据的方式。

将其编码为JSON是一种方法:

var values = response[0].attributes;
var json_values = JSON.stringify(values);
var url_safe_json_values = encodeURIComponent(json_values);
res.redirect("/#blog_post_details/?dataUrl=" + url_safe_json_values

然后你解析JSON(JSON.parse而不是JSON.stringify(与解析相反!)在另一端。