【问题标题】:Encountering a problem when trying to insert JSON data into my postgres database - Node.js尝试将 JSON 数据插入我的 postgres 数据库时遇到问题 - Node.js
【发布时间】:2021-05-23 15:39:46
【问题描述】:

我在尝试将 JSON 数据保存到数据库时遇到问题。现在,我这里有这段代码:

我的服务使用给定参数cep 从 API 检索和缓存数据:

const axios = require('axios');
const NodeCache = require('node-cache'); 

const myCache = new NodeCache();
const pool = require('../database/index');

async function verificaCache(cep) {
  const value = myCache.get(cep);

  if (value) {
    return { city: value, message: 'Data from the cache' };
  }

  const resp = await axios.get(`https://viacep.com.br/ws/${cep}/json/`);

  myCache.set(cep, resp.data, 600);

  return { city: resp.data, message: 'Data not from the cache' };
}

module.exports = verificaCache;

我使用该服务的路线:

const express = require('express');

const cityRouter = express.Router();

const verificaCache = require('../services/VerificaCacheService');

cityRouter.get('/:cep', async (request, response) => {
  const { cep } = request.params;

  try {
    const data = await verificaCache(cep);

    response.status(200).json(data);
  } catch (error) {
    response.status(400).send({ message: 'Erro no retorno do CEP' });
  }
});

module.exports = cityRouter;

它没有问题:

问题来了。当我尝试将数据插入到我的数据库中时,将此代码实现到我的服务中:

const axios = require('axios');
const NodeCache = require('node-cache'); 

const myCache = new NodeCache();
const pool = require('../database/index');

async function verificaCache(cep) {
  const value = myCache.get(cep);

  if (value) {
    return { city: value, message: 'Data from the cache' };
  }

  const resp = await axios.get(`https://viacep.com.br/ws/${cep}/json/`);

  myCache.set(cep, resp.data, 600);
  
  // begins here the code to insert data into the database
  const {
    logradouro, complemento, bairro, localidade, uf,
    ibge, gia, ddd, siafi,
  } = resp.data;

  const values = [cep, logradouro, complemento, bairro, localidade, uf, ibge, gia, ddd, siafi];

  const sql = 'INSERT INTO public.city(cep, logradouro, complemento, bairro, localidade, uf, ibge, gia, ddd, siafi) VALUES ?';

  await pool.query(sql, values); // ends here the code to insert data into the database

  return { city: resp.data, message: 'Data not from the cache' };
}

module.exports = verificaCache;

它不插入任何东西!我尝试只输入city 而不是public.city,但它仍然不起作用。

这是我的index.js 连接文件:

const { Pool } = require('pg');

const pool = new Pool({
  host: 'localhost',
  port: 5432,
  user: 'postgres',
  password: '1234',
  database: 'eureka',
});

pool.connect((err) => {
  if (err) {
    console.log('Erro connecting to database...', err);
    return;
  }
  console.log('Connection established!');
});

pool.end((err) => {
  if (err) {
    console.log('Erro to finish connection...', err);
    return;
  }
  console.log('The connection was finish...');
});

module.exports = pool;

我的数据库没有任何数据:

我直接从dbeaver 创建了表city

如您所见,我的应用程序已连接到数据库:

我是初学者,希望能得到一些帮助

【问题讨论】:

    标签: javascript node.js postgresql express


    【解决方案1】:

    您似乎没有使用任何库来处理将您的参数动态映射到查询本身所需的序数格式(如pg-parameterize),因此行:

    const sql = 'INSERT INTO public.city(cep, logradouro, complemento, bairro, localidade, uf, ibge, gia, ddd, siafi) VALUES ?';

    更具体地说,VALUES ? 部分不应该做任何有用的事情。将其更改为:

    const sql = 'INSERT INTO public.city(cep, logradouro, complemento, bairro, localidade, uf, ibge, gia, ddd, siafi) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)';

    因为pg npm 包正在使用有序参数进行参数化查询。

    查看docs for queries 中的“参数化查询”部分。

    编辑:

    您要么插入新记录,要么出现错误。没有其他选择。如果刷新后您在数据库中没有看到任何新记录,那么您只是在吞下代码中的错误结果。当您使用 async/await 承诺路线时,如果出现问题,代码 await pool.query(sql, values); 将抛出。

    然后,在你的调用者中:

    cityRouter.get('/:cep', async (request, response) => {
      const { cep } = request.params;
    
      try {
        const data = await verificaCache(cep);
    
        response.status(200).json(data);
      } catch (error) {
        response.status(400).send({ message: 'Erro no retorno do CEP' });
      }
    });
    

    你发现了错误。检查 catch 块中的 error 对象持有什么,你会发现有什么问题。

    【讨论】:

    • 我忘了说,但我也试过了,我确实将我的值设置为 ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10),但它仍然没用
    • @werliney 你有什么错误吗?您是否在没有在查询中提供架构的情况下尝试了上述解决方案 - const sql = 'INSERT INTO city(cep, logradouro, complemento, bairro, localidade, uf, ibge, gia, ddd, siafi) VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)';public 是默认架构,因此您不应该提供它。
    • 不,我没有收到任何错误。是的,我试过了,但还是不行,很遗憾
    • 你是对的。我错了,我没有 console.log(error) 看看发生了什么。问题是我在将数据插入数据库之前调用了 pool.end() 。感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 2017-11-19
    • 2014-08-04
    • 1970-01-01
    • 2012-09-09
    • 1970-01-01
    • 1970-01-01
    • 2021-03-22
    • 2014-07-16
    相关资源
    最近更新 更多