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

p8ekf7hl  于 2021-10-10  发布在  Java
关注(0)|答案(2)|浏览(421)

我正在从事NodeJS项目,我正在使用ipstack从ip获取用户数据。无法理解如何从回调函数获取数据并将其插入数据库。
这是我的密码

  1. const ipstack = require('ipstack');
  2. const ip = '103.195.74.60';
  3. ipstack(ip, process.env.IPSTACK, (err, response) => {
  4. console.log(response);
  5. });

在此处插入查询

  1. // create user
  2. await User.create({
  3. fullName,
  4. phone,
  5. email,
  6. nikeName,
  7. ip,
  8. city (come from ip),
  9. zip (come from ip),
  10. browser,
  11. device,
  12. });
ijxebb2r

ijxebb2r1#

您只需要在使用数据库的地方创建数据库 console.log 电话如下:
const ipstack=要求(“ipstack”);

  1. const ip = "103.195.74.60";
  2. ipstack(ip, process.env.IPSTACK, (err, response) => {
  3. // First of all you need to check if there is error
  4. if (err){
  5. // handle error hreer, you might need to use `return`
  6. // at some point to not execute the below code, alternatively
  7. // you could just wrap it in `else`
  8. }
  9. console.log(response); // your orginal `console.log` call
  10. //your database transaction ca be done here,
  11. // create user
  12. await User.create({
  13. fullName,
  14. phone,
  15. email,
  16. nikeName,
  17. ip,
  18. response.city // need to look in documentation
  19. response.zip // or explore the response object terminal
  20. browser,
  21. device,
  22. })
  23. });

我访问响应键的代码部分是推测,如果存在 ipstack 包,或者只是通过探索模式 response 既然你是 console.log .
最后,我建议使用给定的官方文件 lipstick 没有真正维护上次更新是在3年前,请按照您可以使用的官方文档进行添加 fetchaxios 利用
async await 功能,这是当前处理异步代码的现代方法*。

  • 这可能是一个既定的观点。
展开查看全部
06odsfpq

06odsfpq2#

@加桑·马斯拉马尼在遵循您的建议后,工作一直很顺利。检查代码,如果需要代码中的任何改进,请指导我。再次感谢。

  1. // get user ip
  2. const ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
  3. // location details through Api call
  4. const url = `http://api.ipstack.com/${ip}?access_key=${process.env.IPSTACK}`;
  5. async function locationInfo() {
  6. try {
  7. const result = await axios.get(url);
  8. const data = await result.data;
  9. return data;
  10. } catch (error) {
  11. console.log(error);
  12. }
  13. }
  14. const locInfo = await locationInfo();
  15. // City name
  16. const location = `${locInfo.city},${locInfo.country_name}`;
  17. // zip code
  18. const { zip } = locInfo;
展开查看全部

相关问题