为了账号安全,请及时绑定邮箱和手机立即绑定

无法将从 api 获取的变量添加到数据库

无法将从 api 获取的变量添加到数据库

白猪掌柜的 2021-11-12 16:43:27
问题是数据库中来自 api 请求的数据的字段应该是“0 字段”。我认为这是因为 mongo 在 api 响应在对象的变量中之前将对象插入到数据库中。所以我想我需要让数据库插入函数等到 api 请求完成。有谁知道我怎样才能完成这件事?const express = require('express');const bodyParser = require('body-parser');const exphbs = require('express-handlebars');const path = require('path');const fs = require('fs');const fetch = require('node-fetch');var mongodb = require('mongodb')var mongoDbQueue = require('mongodb-queue')const url = 'mongodb://localhost:27017/'const client = new mongodb.MongoClient(url, { useNewUrlParser: true })const app = express();// View engine setupapp.engine('handlebars', exphbs());app.set('view engine', 'handlebars');app.set('views', __dirname);// Static folderapp.use('/public', express.static(path.join(__dirname, 'public')));// Body Parser Middlewareapp.use(bodyParser.urlencoded({ extended: false }));app.use(bodyParser.json());app.get('/', (req, res) => {  res.render('main');});app.post('/send', (req, res) => {  var item = {  name: req.body.name,  age: req.body.age,country: req.body.country,  isValid: fetch(*/normaly working url inside here*/)        .then(res => res.json())      .then(data => isValid = data)      .then(() => console.log(isValid))}client.connect(err => {    const db = client.db('test')    const queue = mongoDbQueue(db, 'my-queue')  queue.add(item, (err, id) => {   })  })});app.listen(3000, () => console.log('Server started...'));.then(() => console.log(equivalent)) 给了我正确的值,所以它与 api 无关
查看完整描述

2 回答

?
慕尼黑的夜晚无繁华

TA贡献1864条经验 获得超6个赞

不太清楚您要在这里实现什么,但我的猜测是,当在 /send 路由中确定了 fetch 承诺时,您想添加一个数据库条目。在这种情况下,您需要像这样重构代码:


const express = require('express');

const bodyParser = require('body-parser');

const exphbs = require('express-handlebars');

const path = require('path');

const fs = require('fs');

const fetch = require('node-fetch');


var mongodb = require('mongodb')

var mongoDbQueue = require('mongodb-queue')


const url = 'mongodb://localhost:27017/'

const client = new mongodb.MongoClient(url, { useNewUrlParser: true })


const app = express();


// View engine setup

app.engine('handlebars', exphbs());

app.set('view engine', 'handlebars');

app.set('views', __dirname);


// Static folder

app.use('/public', express.static(path.join(__dirname, 'public')));


// Body Parser Middleware

app.use(bodyParser.urlencoded({ extended: false }));

app.use(bodyParser.json());


app.get('/', (req, res) => {

    res.render('main');

});


app.post('/send', (req, res) => {

    let name = req.body.name;

    let age = req.body.age;

    let country = req.body.country;

    fetch( /* normaly working url inside here */)

        .then(res => res.json())

        .then(data => {

            let item = { name, age, country, isValid: true };

            // data is ready to be used or added to the database at this point:

            client.connect(err => {

                const db = client.db('test')

                const queue = mongoDbQueue(db, 'my-queue')

                queue.add(item, (err, id) => {

                })

            })


        })

        .catch((error) => console.log(error));


});


app.listen(3000, () => console.log('Server started...'));



查看完整回答
反对 回复 2021-11-12
?
jeck猫

TA贡献1909条经验 获得超7个赞

问题在于 fetch API 的异步特性。isValid 中的值直到稍后的时间点才会解析。您也错误地使用了该值。


下面的代码等待响应,设置值,并在正确的范围内更新数据库。


app.post('/send', (req, res) => {

 fetch(*/normaly working url inside here*/)  

      .then(res => res.json())

      .then(isValid => {

       var item = {

        name: req.body.name,

        age: req.body.age,

        country: req.body.country,

        isValid //same as isValid : isValid

      }

      client.connect(err => {

       if(!err) { // error check

         const db = client.db('test');

         const queue = mongoDbQueue(db, 'my-queue');

         queue.add(item, (err, id) => {})

       }

      });

    });

});


查看完整回答
反对 回复 2021-11-12
  • 2 回答
  • 0 关注
  • 128 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信