Asynchronous functions within the next context

Hello there! I am trying to send the client's IP address from the frontend in a Next.js application to the backend.

To retrieve the IP, I am using the following function:

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

and then sending it using axios post.

    getIP().then(ipAddress => {
       axios.post('/api/ip', {

                body: ipAddress

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

The server is able to display the IP address in the console, but...

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

Answer №1

It is important to note that when dealing with an asynchronous function, you are not receiving a string directly; instead, you are getting a promise of a string, which essentially means it's a promise for the data.

The data contained within the promise can only be accessed once the promise has been resolved.

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(...)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Named Graph's Title on Image Save in Echarts

Is there a way to give a title to the image graph saved in Echarts, as Echarts does not have this option available? Any suggestions on how we can achieve this? Here is a link for reference from Echarts that provides the 'saveAsImage' option: Ch ...

Introduce regex in the middle

If I have a string in JavaScript like so: "test test hello test test" I understand how to replace 'hello' with 'byebye': replace("hello","byebye"); However, what is the most efficient method to add 'byebye' immediately afte ...

Add a new class to an element located in a separate div using JavaScript

$(document).ready(function() { $('.btn').click(function() { $(this).parent().addClass('show'); }); }) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div clas ...

Deleting an ID from an array within a document using Node.js Mongoose

In my model document, there is an array that I am working with. I want to be able to remove a specific ID from this array. Is it possible to do so? Below is what I attempted. module.exports.RemoveFavourite = async (req, res, next) => { try { cons ...

The variable within my function is not being cleared properly despite using a jQuery function

Recently, I encountered an issue with a function that displays a dialog box to ask users if their checks printed correctly. Upon clicking on another check to print, the "checked_id" value remains the same as the previously executed id. Surprisingly, this i ...

Is the reordering of items in an Angular JS array causing a malfunction with the first item

It appears that there may be a syntax error present in my code. Within my controller, I have a set of 4 functions: adding a new item, deleting the current item, moving an item backward (up) in the array, and moving an item forward (down) in the array. Al ...

Retrieving the text of a selected option by its value

I need to create a menu that returns text based on a given value. For example, if the value is 0, I want it to return “zero”, and if it's 1, then “one”, and so on. I don't need to know which option is selected or auto-select anything, I j ...

Node.js throws an error with the message "Unexpected token *" while utilizing the robe

Currently, I'm working on a Node.js application where I'm attempting to utilize the node module named robe. Unfortunately, I encountered an error message when trying to launch the app: function* promiseToGenerator(promise) { ^ Error l ...

Use `$$state: {…}` within the request rather than the data

When attempting to send a request with data, I am only getting "f {$$state: {…}}" in the console. $scope.createTask = function () { var req = $http.post('api/insert', { title: $scope.newTitle, description: ...

Cannot locate module: Unable to resolve 'encoding' in '/Users/dev/node_modules/node-fetch/lib'

Currently, I am working with next.js version 13.4.5 and firebase version 10.1.0. Every time I execute npm run dev, a warning is displayed initially. Eventually, an error message pops up in the terminal after the warning persists for some time. I am u ...

Error: undefined callback function in asynchronous parallel execution

Encountering the error message "callback is not defined" while attempting to utilize async.parallel has left me puzzled. Most examples of async.parallel demonstrate functions being inline, as shown in the async documentation here: https://caolan.github.io/ ...

(Typescript) The 'window' property is not present in the 'Global' type

Currently, I am utilizing Mocha/Chai for unit testing and have decided to mock the window object like so: global.window = { innerHeight: 1000, innerWidth: 1000 }; As expected, TSLint is raising an issue stating: Property 'window' does not ex ...

Iframe form submissions

I am interested in accomplishing the following task. My objective is to submit a form to my booking engine and show the results on either a new page or within a Div element. Ideally, when the user clicks the submit button, it would display an Iframe or re ...

What is the best way to navigate through a complex array in React that includes objects and nested arrays?

I have been working on a JavaScript array that includes subobjects with arrays nested in them. My goal is to iterate through the entire parent object using React. Although I attempted the following approach, unfortunately it did not yield the desired outco ...

Using the JQuery template with $.get function does not produce the desired result

Working on populating a table using a Jquery Template can be tricky. One challenge is incorporating a json file via an ajax call for the population process. $(document).ready(function() { var clientData; $.get("/webpro/webcad/lngetusuario", funct ...

Why isn't the page showing up on my nextjs site?

I've encountered an issue while developing a web app using nextjs. The sign_up component in the pages directory is not rendering and shows up as a blank page. After investigating with Chrome extension, I found this warning message: Unhandled Runtime ...

Failed to establish a webSocket connection to 'ws://localhost:8000/socket.io/?EIO=4&transport=websocket' while attempting to connect the socket.io client to the server

I'm struggling to establish a websocket connection between my Next.js clientside and Node.js server side. I keep encountering this error message: webSocket connection to 'ws://localhost:8000/socket.io/?EIO=4&transport=websocket' failed: ...

What is the reason behind the jQuery only functioning properly on Internet Explorer 8 on this particular page and no other browsers?

I recently created a webpage utilizing jQuery: The functionality on the page should change music images to represent different key signatures when switching from 'Higher Key' to 'Lower Key' in the combo box. While this works perfectly ...

What is the best way to iterate over each character in a string and trigger a function in JavaScript?

I am currently working on a project to create a random password generator. The code responsible for generating the password is functioning correctly. However, I am facing an issue with converting the characters of the password into phonetic equivalents. I ...

Jquery double-click Event Not Functioning Properly

I've been attempting to toggle the visibility of my footer navbar while also changing the chevron icon. When the navbar is hidden, I want the chevron pointing up to be displayed, and when the navbar is shown, I want the chevron pointing down to be dis ...