修改来自 API 的数据并保存在 postgreSQL 中
Modifying data from API and save in postgreSQL
我想从 public API 中获取一些数据,然后修改这些数据。例如,我将在 Postgis 的地理中添加一个 Point(long, lat)。但是,在到达那里之前,我需要从 public API 中获取数据。到目前为止我已经尝试过了,但它的逻辑似乎没有意义。
向数据库中插入数据工作正常,我已正确设置。但是,当我尝试在 JSON 函数中执行此操作时会出现问题。
require('dotenv').config()
const express = require('express')
const fetch = require('node-fetch');
const app = express();
const db = require("./db");
app.use(express.json());
async function fetchDummyJSON(){
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(res => res.json())
.then((json) => {
await db.query("INSERT INTO logictest(userId,id,title,completed) values(,,,)",[json.userId+1,json.id,json.title,json.completed])
});
}
fetchDummyJSON()
app.get('/', (req, res) => {
res.send('Hello World!')
});
const port = process.env.PORT || 3001
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
我一直收到 SyntaxError: await is only valid in async functions and the top-level body of modules;但是,据我所知,fetchDummyData() 是一个异步函数。有没有办法使它更有意义或使它起作用?我要 PERN 堆栈。
这也是一个函数:
.then((json) => {
await db.query("INSERT INTO logictest(userId,id,title,completed) values(,,,)",[json.userId+1,json.id,json.title,json.completed])
});
尝试
.then(async (json) => {
await db.query("INSERT INTO logictest(userId,id,title,completed) values(,,,)",[json.userId+1,json.id,json.title,json.completed])
});
我想从 public API 中获取一些数据,然后修改这些数据。例如,我将在 Postgis 的地理中添加一个 Point(long, lat)。但是,在到达那里之前,我需要从 public API 中获取数据。到目前为止我已经尝试过了,但它的逻辑似乎没有意义。
向数据库中插入数据工作正常,我已正确设置。但是,当我尝试在 JSON 函数中执行此操作时会出现问题。
require('dotenv').config()
const express = require('express')
const fetch = require('node-fetch');
const app = express();
const db = require("./db");
app.use(express.json());
async function fetchDummyJSON(){
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(res => res.json())
.then((json) => {
await db.query("INSERT INTO logictest(userId,id,title,completed) values(,,,)",[json.userId+1,json.id,json.title,json.completed])
});
}
fetchDummyJSON()
app.get('/', (req, res) => {
res.send('Hello World!')
});
const port = process.env.PORT || 3001
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
我一直收到 SyntaxError: await is only valid in async functions and the top-level body of modules;但是,据我所知,fetchDummyData() 是一个异步函数。有没有办法使它更有意义或使它起作用?我要 PERN 堆栈。
这也是一个函数:
.then((json) => {
await db.query("INSERT INTO logictest(userId,id,title,completed) values(,,,)",[json.userId+1,json.id,json.title,json.completed])
});
尝试
.then(async (json) => {
await db.query("INSERT INTO logictest(userId,id,title,completed) values(,,,)",[json.userId+1,json.id,json.title,json.completed])
});