【问题标题】:Async function in next下一个异步函数
【发布时间】:2020-04-27 05:57:35
【问题描述】:

美好的一天! 我想将客户端 ip 从 next.js 中的前端发送到后端

为了获取 ip,我使用这个函数:

    async function getip() {
        var c = await publicIp.v4();
        return c;
    }
    export default getip;

并使用 axios 帖子发送。

    getip().then(ip => {
       axios.post('/, {

                body: ip

            }). then((res) => {}...}

服务器在控制台中显示 ip 但是

var IP = req.body;
  console.log(IP); // ***undefined***

【问题讨论】:

  • function getip() { 还是async function ip() {?正如发布的那样,这是一个语法错误。
  • 很可能,ip 是一个承诺。发送请求前需要等待结果。
  • 什么是publicIp.v4();?您谈论的“下一个”框架是什么(标签看起来不对)?为什么要在请求正文中发送客户端 IP 地址?只发送一个空请求,后端无论如何都会收到请求发送者的IP。
  • Next.js。我有 2 页。从 index.js 我调用函数 getip(),其中包括异步函数 ip(){}。
  • 好吧,“包括”这个功能是不够的。您需要实际调用它并返回它的承诺。请发布getip的完整实际代码。

标签: javascript asynchronous axios next.js


【解决方案1】:

所以事情是你可能期待一个字符串,但异步函数给你一个字符串的承诺,顾名思义就是一个承诺。

只有当该承诺得到解决时,您才能使用包含的数据。

function getIpSomehow() {
  return new Promise(res => {
      setTimeout(() => {
          res("127.0.0.1")
        },500)}
      )
  }
  async function getIp() {
    //var c = await publicIp.v4();
    const c = await getIpSomehow();
    return c;
  }

  getIp().then(ip => {
    //all axios stuff in here
    console.log(ip)
  })
  //however as you may see getIp function is quite useless so we could as well do 
  // getIpSomehow().then(...)

【讨论】:

  • 是的,它有效。应该添加异步调用函数 getIp().then(..... 谢谢!在服务器 req.body 中显示 IP。但是当尝试相等时 var IP = req.body console.log(IP); // undefined is any获取ip值的方法?
  • req.body 是一个对象,您应该使用您指定的密钥获取 ip,例如 const IP = req.body.whateverYouSetHereInTheReq;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-07
  • 2021-04-14
  • 2020-09-18
  • 1970-01-01
相关资源
最近更新 更多