API Integration

How to Integrate custom API?

Please follow the below steps to make the custom API working.

  1. Let's assume that our API's URL is "https://jsonplaceholder.typicode.com/posts"
                                                    
        import axios from 'axios'
            ...
        mounted() {
            axios.get('https://jsonplaceholder.typicode.com/posts').then(data=>{
                this.data=data;
            }).catch(e=>{
                console.log('error',e);
            })
        },
                                                    

  2. let's setup auth middleware with api.

    to setup middleware change below code in src/router/index.js. this will check user is authenticated or not.

        
            import axios from 'axios'
            ...
            
            router.beforeEach(async (routeTo, routeFrom, next) => {
        
                const authRequired = routeTo.matched.some((route) => route.meta.authRequired)
                
                if (!authRequired) return next()
                
                axios.defaults.headers.common['authorization'] = 'Bearer ' + localStorage.getItem('jwt') // for all requests
                await axios.get('https://jsonplaceholder.typicode.com/posts').then((data) => {
                    localStorage.setItem('userdata', JSON.stringify(data.user))
                    localStorage.setItem('userid', data.user._id)
                    next()
                }).catch(() => {
                    next({ name: 'login', query: { redirectFrom: routeTo.fullPath } })
                });
            })
        

  3. Now set post method api for signup with below function
                                                    
        import axios from 'axios'
            ...
        methods: {
            async tryToRegisterIn() {
                this.submitted = true;
                // stop here if form is invalid
                this.v$.$touch();
                const result = await axios.post('https://jsonplaceholder.typicode.com/posts', {
                  email: this.email,
                  password: this.password,
                  confirm_password: this.confirm_password
                })
                if (result.data.status == 'errors') {
                  this.isRegisterError = true
                  return this.regError = result.data.message;
                }
                localStorage.setItem('jwt', result.data.token)
                this.$router.push({
                  path: '/'
                });
        
              },
            },
                                                    

© Vixon.
Design & Develop by Themesbrand