Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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'
        }
    })
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
    });
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading