【问题标题】:send JSON array from Express to Angular2将 JSON 数组从 Express 发送到 Angular2
【发布时间】:2017-01-06 19:37:57
【问题描述】:

我正在尝试发送一个包含来自猫鼬的错误的自制数组,它使数组正常。 代码如下:

student.save(function(err, student) {
    if(err)
        var errors = [];
        for (field in err.errors) {
            errors.push({error: err.errors[field].message})
        };
        res.contentType('application/json').status(500).send(JSON.stringify(errors));
    res.status(200).json(student);
});

它将创建一个这样的数组:

[ { error: 'Error, expected `_id` to be unique. Value: `111111` },
{ error: 'Error, expected `email` to be unique. Value: `test@test.com` } ]

但是发送到angular2时,是作为字符串存储的

_body: "[{"error":"Error, expected `_id` to be unique. Value: `111111`"},{"error":"Error, expected `email` to be unique. Value: `test@test.com`"}]"
headers: ...
ok: false
status: 500
statusText: "OK"
type: 2
url: ...

目前我正在尝试将 'err' 记录到 Angular2 中的控制台。但我尝试过 JSON.parse 并收到此错误:EXCEPTION: SyntaxError: Unexpected token o in JSON at position 1

另外,我尝试了许多不同的发送数组的方法,我尝试过.json(errors); 而不是.send(JSON.stringify(errors));

任何想法将不胜感激

编辑 angular2代码:

err => console.log(err)

我已经尝试过JSON.parse(err) 并且我已经尝试过private errors = []; 并将“err”插入到该数组中,但没有任何变化,我仍然得到相同的结果

【问题讨论】:

    标签: arrays json node.js express angular


    【解决方案1】:

    试试这个东西..

    student.save(function(err, student) {
      if (err) {
        var errors = [];
        for (var field in err.errors) {
          errors.push({
            error: err.errors[field].message
          });
        }
        return res.contentType('application/json').status(500).send(errors);
      }
      res.status(200).json(student);
    });
    

    【讨论】:

    • 打印console.log(err)会得到什么?从你得到err 值的地方你能把角度代码放在你的问题中吗?
    • console.log(err) in angular2 ???这就是它产生的东西:_body: "[{"error":"Error, expected _id` 是独一无二的。值:111111"},{"error":"错误,预计 email 是唯一的。值:test@test.com"}]" 标题:... ok: false status: 500 statusText: "OK" type: 2 url: ...` 在主帖中提到,它将所有结果存储到 '_body' ? ?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-15
    • 1970-01-01
    • 2019-04-24
    • 1970-01-01
    • 2021-10-07
    相关资源
    最近更新 更多