Home > Mobile >  how to send api token key with React fetch in laravel?
how to send api token key with React fetch in laravel?

Time:12-13

this my code : how to make it pro? , also what's the best Laravel API lib for this case?

    likePost() {
    fetch("api/like_post" , {
        method: "POST",
        headers: {
            'Key': '11111111111111111'
        }
    })
    }

CodePudding user response:

I think you can check out this awsome Laravel Package for APIs : https://github.com/ejarnutowski/laravel-api-key ,

and you can make your code better by this syntax :

first add new state for likes

   this.state = {
        likes: 0,
    };

then bind the function :

    this.likePost = this.likePost.bind(this);

and create the final function like this :

    likePost(post_id, user_id) {
    fetch("api/like_post" , {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "Accept": "application/json",
            'X-Authorization': 'KkKf87BOncnOGwzjLBG8Isd87T42D1yOJJNoUMsrjmUkqSIxXmHG4XPZ07UQM0Pi'
        },
        body: JSON.stringify({
            "post_id": post_id,
            "user_id": user_id
        })
    })
    .then(res => res.json())
    .then(likes => this.setState({likes:likes}))
    .catch(error => {
       // Log Error
       console.log(error)
    });
}
  • Related