RandomUser
RandomUser

Reputation: 123

Set access token in Loopback with React

I'm new to Loopback and Reactjs. I wanted to build an application with User login, logout functionality. But, I'm confused how to set the Access Token in Loopback with react front end and further access the other methods. I'm using the User Model provided with Loopback.

So far, I've written this little code, for access login, but I'm confused how to further set the access Token to authenticate.

import React, {Component} from 'react';
import axios from 'axios';

class Login extends Component{

    constructor(props) {
        super(props);
        this.state = {
            "username": ""
            }
        }

    login(newUser) {
        axios.request({
            method:'post',
            url:'http://localhost:3000/api/Users/login',
            data: newUser
          }).then(response => {
            this.props.history.push('/');
          }).catch(err => console.log(err));
    }

    onSubmit(e){
        const newUser = {
            username: this.refs.username.value,
            password: this.refs.password.value
        }
        this.login(newUser);
        e.preventDefault();
    }
}

This code snippet as expected does not set the Access Token, so I was wondering if I require some additional middleware or something to do it.

Upvotes: 2

Views: 329

Answers (1)

imran ali
imran ali

Reputation: 383

try this code.

login(newUser) {
        axios.request({
            method:'post',
            url:'http://localhost:3000/api/Users/login',
            data: newUser
          }).then(response => {
         localStorage.ptspotter_accessToken = response.data.id;
          localStorage.ptspotter_userId = response.data.userId
            auth0.login();
            this.props.history.push('/');
          }).catch(err => console.log(err));
          window.login();
    }

you can store login userId and token in localStorage and access anywhere.

Upvotes: 1

Related Questions