【发布时间】: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