我如何通过Node.js返回MySQL JSON

时间:2019-11-17 17:40:59

标签: javascript mysql node.js bots discord

详细信息:下面有2个项目(API和BOT Discord)。 我可以从MySQL中获取数据并将其显示在网络上。但我不能在json中显示,而无需先通过数组。

我需要在json中返回它,以便我可以从BOT(也在nodejs中)获取数据

因此,我想删除 [] 键以使我的项目完美。

criminals.js-> Discord BOT

const res = await axios.get('http://localhost:3001/api/criminals/49');
   console.log(res.data.id);

已经尝试更改 res.data.id ,但结果没有更改。

CriminalsControll.js-> API

async show(req, res) {
        // Show unique details

        var results = db.query(`SELECT * from lspd WHERE id = ${req.params.id}`, function (error, results, fields) {
            if (error) throw error;

            //make results 
            var resultJson = JSON.stringify(results);
            resultJson = JSON.parse(resultJson);
            var apiResult = {};

            //add our JSON results to the data table
            apiResult.data = resultJson;

            return res.json(resultJson);
        });

    },

WEB返回->

[
  {
    "id": 49,
    "nom": "Filipe",
    "telephone": "232323",
    "steam": "12345678",
    "crime": "Roubo de veiculo / Tentativa de fuga / Tentativa de Homicidio a Policial.",
    "sanction": "Pegou 1000 de multa por Furto de veiculo. Foi preso por 5 Anos por Roubo de veiculo + 5 anos de tentativa de Fuga",
    "user_id": 5,
    "DateHour": "2019-11-16T21:00:00.000Z"
  }
]

需要任何帮助:}

1 个答案:

答案 0 :(得分:0)

您将返回一个javascript数组,因此将[]放在对象周围。为了访问第一个对象,您必须使用以下方法之一:

假设以下变量是您的API响应:

const array = [{ id: 1 }]

通过第一个阵列键进行访问:

let criminal = array[0]

console.log(criminal) // {id: 1}
console.log(criminal.id) // 1

或使用数组解构(仅在ES6中可用):

let [first] = array

console.log(first) // {id: 1}
console.log(first.id) // 1

或使用lodash /下划线:

let criminal = _.first(array)

console.log(criminal) // {id: 1}
console.log(criminal.id) // 1

如果您只想从API(nodejs)返回对象

// async show ()
let [criminal] = resultJson
return res.json(criminal);