DEV Community

Jasper Aurelio Villas
Jasper Aurelio Villas

Posted on

Authentication

If you're performing a login with a username and password instead of an email, the structure of the Axios request is almost the same. You simply change the field from email to username.

Example Login Request with Username and Password using Axios:

const axios = require('axios');

const loginData = {
  username: 'testUser',  // Use 'username' instead of 'email'
  password: 'password01'
};

axios.post('https://your-authentication-endpoint.com/api/login', loginData)
  .then(response => {
    // The server typically returns an authentication token on successful login
    const authToken = response.data.token;  // Adjust according to your API's response
    console.log('Login successful. Token:', authToken);

    // Optionally store the token in local or session storage for future use
    // localStorage.setItem('authToken', authToken);
  })
  .catch(error => {
    console.error('Login failed:', error.response ? error.response.data : error.message);
  });
Enter fullscreen mode Exit fullscreen mode

Key Changes:
loginData: The key for the username field is now username (instead of email).
POST Request URL: The login URL remains the same (replace 'https://your-authentication-endpoint.com/api/login' with your actual API endpoint).

Notes:
Make sure your API endpoint expects username in the request body.
The Authorization header works the same way after the login (if your server returns a token). You can then use this token in subsequent requests just like you would with an email-based login.
Here's an example of what the API might return:

json

{
  "token": "your-jwt-token-here",
  "user": {
    "id": 1,
    "username": "testUser"
  }
}
Enter fullscreen mode Exit fullscreen mode

In that case, you can extract the token from the response and store or use it for future authenticated requests.

Top comments (0)