微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从回调存储数据库中的数据

如何解决从回调存储数据库中的数据

我正在处理 node 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,});

解决方法

您只需在使用 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 假设您是 { {1}}。

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

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

,

@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;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。