【问题标题】:store data from database from call back从回调中存储数据库中的数据
【发布时间】:2021-10-01 19:45:15
【问题描述】:

我正在处理节点 js 项目,我正在使用 ipstack 从 IP 获取用户数据。无法理解如何从回调函数中获取数据并将其插入到我的数据库中。

这是我的代码

const ipstack = require('ipstack');

const ip = '103.195.74.60';
ipstack(ip, process.env.IPSTACK, (err, response) => {
    console.log(response);
});

在此处插入查询

// create user
await User.create({
    fullName,
    phone,
    email,
    nikeName,
    ip,
    city (come from ip),
    zip (come from ip),
    browser,
    device,
});

【问题讨论】:

  • 有人来帮我...

标签: javascript node.js callback asynccallback


【解决方案1】:

您只需要将数据库牵引到您使用console.log 调用的确切位置,如下所示:

const ipstack = require("ipstack");

const ip = "103.195.74.60";
ipstack(ip, process.env.IPSTACK, (err, response) => {
  // First of all you need to check if there is error
  if (err){
    // handle error  hreer, you might need to use `return`
    // at some point to not execute the below code, alternatively 
    // you could just wrap it in `else`
               }
    console.log(response); // your orginal `console.log` call

  //your  database transaction ca be done here,
  // create user
  
            await User.create({
                fullName,
                phone,
                email,
                nikeName,
                ip,
                response.city // need to look in documentation 
                response.zip // or explore the response object terminal 
                browser,
                device,
            })
            
});

我访问响应键的代码部分是推测,如果存在 ipstack 包,您只需要查找文档,或者只需探索架构 response (假设您是 console.log)。

最后,我建议使用official documentation,因为lipstick 没有真正维护,最后一次更新是 3 年前,按照官方文档添加,您可以使用 fetchaxios 并采取async await 功能的优势,这是当前处理异步代码的现代方法*。

*这可能是一个约定的视角。

【讨论】:

  • 感谢您的宝贵回复,我将查看官方文档。有什么方法可以创建两个单独的函数。
  • 您可以在单独的模块/文件中创建函数,然后将其导入并在回调中进行函数调用。
  • 按照您的建议后,它一直运行顺利。检查代码,如果需要对代码进行任何改进,请指导我。再次感谢。
【解决方案2】:

@Ghassan Maslamani 在听从您的建议后,它一直在顺利运行。检查代码,如果需要对代码进行任何改进,请指导我。再次感谢。

    // get user ip
    const ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
    // location details through Api call
    const url = `http://api.ipstack.com/${ip}?access_key=${process.env.IPSTACK}`;
    async function locationInfo() {
        try {
            const result = await axios.get(url);
            const data = await result.data;
            return data;
        } catch (error) {
            console.log(error);
        }
    }
    const locInfo = await locationInfo();
    // City name
    const location = `${locInfo.city},${locInfo.country_name}`;
    // zip code
    const { zip } = locInfo;

【讨论】:

  • 第一眼看起来不错,我只注意localInfo,当locationIfo函数中抛出错误时,localInfo的值将是未定义的,因此在@987654325 @你没有返回任何东西....说下一行你得到localInfo.city,会抛出错误:Uncaught TypeError: Cannot read property 'city' of undefined...等
猜你喜欢
  • 2013-02-20
  • 1970-01-01
  • 2021-11-25
  • 1970-01-01
  • 2021-11-21
  • 2022-10-25
  • 1970-01-01
  • 2014-09-16
  • 1970-01-01
相关资源
最近更新 更多