The axios post request with async/await does not support the "then" function

Hi there! I am currently in the process of registering a user through a POST request.

I have implemented axios along with async/await for this task. However, I'm encountering an error that says register.then is not a function. Can someone please provide assistance?

async sendUserData() {
  try {
    const register = await axios.post('/register', {
      email: this.register.email.trim(),
      password: this.register.password.trim(),
    });
    register.then(
      response => {
        console.log(response);
      }
    );
  } catch (e) {
    console.log(e);
  }
}

Answer №1

The await command waits for a promise to be resolved (which means it handles the then method internally) but it does not directly return a promise. Instead, await returns the result of the promise.

Therefore, the correct approach to achieve your goal is:

async sendUserData() {
  try {
    const response = await axios.post('/register', {
      email: this.register.email.trim(),
      password: this.register.password.trim(),
    });

    console.log(response);

  } catch (e) {
    console.log(e);
  }
}

However, keep in mind that the async keyword itself returns a promise. Therefore, you should invoke your function like this:

sendUserData().then(console.log('done'));

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

Updating the Position of an Element in ElectronJS (e.g. Button, Label, etc)

Is there a way to change the positioning of a button in a window using JavaScript and Electron? I am trying to create new input boxes next to existing ones, but they always appear below the last one created. Is it possible to specify x and y coordinates fo ...

Can you explain the variance between Facebook HTML and traditional HTML5?

A client has recently requested my services to create a basic Facebook page for them. Since I am not well-versed in the realm of Facebook webpages, can you guide me towards the right sources to answer the following question: What distinguishes HTML5 from ...

Quickly showing information following an API request with React hooks

Why is the second line not displaying data instantly like the first line from props? I want both lines to display immediately. When I click on a button, it triggers an API call and updates the state with incoming data. However, the second line requires an ...

The error message that keeps popping up is saying that it cannot access the property "username" as it is undefined

signup.js const SignupForm = () => { const [username, setUsername] = useState(""); const [password, setPassword] = useState(""); const handleSignup = () => { fetch("/signup", { method: "post", header ...

What is the best method to access the query string or URL within an AJAX page?

I recently discovered how to extract query string parameters from this helpful resource. However, I am facing difficulty retrieving the URL within the requested page via ajax. For instance: <div class="result"></div> <script> $(func ...

How to display an HTML element conditionally with v-if based on a variable's value

Looking for a way to display a <div> element, including nested <div>s, based on the value of a variable. I'm currently using v-if, but open to better suggestions. I attempted wrapping the entire <div> in a <template v-if> as s ...

Error: Unable to return callback response from NodeJs function

I have a function that handles the process of reading a private key from the filesystem and generating a JWT token. The code successfully reads the file and creates a token, but it encounters an issue when attempting to callback to the calling function. De ...

Tips for leveraging Vuetify in a chrome extension without the need for build or bundler tools

I am currently working on a Chrome extension and my goal is to integrate Vue.js and Vuetify for the popup UI design. Since the extension utilizes manifest version 3 which imposes stricter CSP restrictions compared to v2, I need to be mindful of these lim ...

Ways to verify browser rollover support (as some mobile devices lack a cursor)

I am currently exploring options to determine if rollover events are supported for navigation. If not, I plan to switch to click events. I have reviewed jQuery.Support and Modernizr but haven't come across anything that directly addresses my issue. T ...

What is the process to insert a record into a table by triggering an AJAX call upon clicking "save

I'm looking to dynamically update a table with data from a database using AJAX. Specifically, I want the table to reflect any new records added by the user without having to refresh the entire page. Below is my JavaScript code snippet for handling thi ...

Transforming JSON information for Google chart data table

I am currently working on converting JSON data into a suitable format for a Google Chart visualization: var jsonData = {"Battery Voltage, (A)": {"2017-11-11T00:00:00.000Z":12.3, "2017-11-11T00:01:00.000Z":12.35, ...

Tips for preserving the encoded value of a variable in base64?

I have a large .zip file containing numerous geographic coordinates that I am converting to base64 format. Although I can successfully convert the file to base64, I am encountering an issue in storing the resulting variable for future use. My current app ...

An error is raised when attempting to refactor [].concat.apply([], [x]) to [].concat(x)

When attempting to refactor Array.prototype.concat.apply([], [x]) to [].concat(x), I encountered the following error message: No overload matches this call. Overload 1 of 2, '(...items: ConcatArray<never>[]): never[]', gave the following ...

The background property does not support linear-gradient in CSS

I am currently working on creating a tree structure using the vue-orgchart library (link) Everything is functioning correctly, but I am interested in changing the green background color of the node (ignoring the white portion). https://i.sstatic.net/EEcd ...

Assigning a value to a cell depending on a specific condition

Currently, I have a column connected to a field known as state. The possible values for this field are either S or L. My objective is to map these values as follows: S => Short, L => Long The binding is structured in the following way: $scope.grid ...

The battle between Google Visualization API JSON and ArrayToDataTable in Python, a nightmare of data types

Initially, I developed a basic static google visualization page using python The python source code is as follows: def print_graph_script(temp_table): # google chart snippet chart_code=""" <script type="text/javascript" src="https://www.g ...

Encounter TypeScript error when using getFirebaseAdmin from next-firebase-auth

I am currently utilizing a package called next-firebase-auth. I am encountering an issue when calling getFirebaseAdmin from next-firebase-auth and attempting to use it, specifically when using db as a reference in doc(db). The error message received is: ...

What sets apart genuine user interactions from programmatically generated actions?

Working with webkit notifications on Chrome has presented a challenge. The window.webkitNotifications.requestPermission method must be called from a user action, such as a click. Attempting to call it at any other time will not have any effect and will not ...

"Effortlessly handle adding and removing items with a single button using

I am working on creating a button functionality where clicking it will either add or delete a record from the database. This button serves as a 'favorite' feature. The desired behavior is as follows; Upon clicking the 'fav' button, th ...

Lack of Ajax query string parameters

To implement a functionality where clicking on a delete button in the UI triggers a service method that retrieves data from a database and displays it in a popup, I need to call a specific method in an Action class. The task id and command name (method nam ...