Search code examples
reactjspostaxiosauthorization

How do I resolve this bug when setting up log in authentication system in react?


Please I need a set of expert eyes on these real quick :

what would happen if the error did not come up

enter image description here

header: enter image description here

body: enter image description here

The login page would collect the user's gmail and password , send it to the login url and get an object containing the authorization token would be returned. Works perfectly on postman.

Inside vscode :

This is the function handle the authorization:

  const [loginInput, setLoginInput] = React.useState({
      email: '',
      password: ''
  })


const handleSubmit = async (e) =>{
    e.preventDefault();
    try{
      const response = await axios.post('https://adscamp.thevootblog.com/api/v1/users/login',
        JSON.stringify(loginInput.username, loginInput.password),
        {
          headers: { 'Content-Type' : 'application/json',
          'Authorization': `Bearer ${response?.token}`
         }
        }
      );
      console.log(response)

    }catch(err){
         console.log(err)
    }
  }

I'm not getting the object

enter image description here "cannot access 'response' before initialization" ,which means response is empty.

extra information : I imported axios into login.js file from another file :

api(folder) => api.js

import axios from "axios";

export default axios.create({
    baseURL: 'http://localhost:3000'
})

Solution

  • This is node.js code

    const axios = require('axios');
    
    const getToken = async () => {
        try {
            const response = await axios.post(
                url = 'https://adscamp.thevootblog.com/api/v1/users/login',
                data = {
                  'email': '[email protected]',
                  'password': '<your password>'
                },
                config = {
                  headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                  }
                }
            )
            return Promise.resolve(response.data.token)
        } catch (error) {
            return Promise.reject(error)
        }
    }
    
    getToken()
        .then((token) => {
            console.log(JSON.stringify(token, null, 4))
        })
        .catch(error => console.log(error));
    

    Install dependency

    npm install axios
    

    Result

    enter image description here

    Curl commend

    curl --location 'https://adscamp.thevootblog.com/api/v1/users/login' \
    --silent \
    --header 'Accept: application/json' \
    --header 'Content-Type: application/json' \
    --data-raw '{
      "email": "[email protected]",
      "password": "your password"
    }' | jq
    

    Result enter image description here

    Now you needs to hide your password.