PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, April 20, 2022

[FIXED] How to get Laravel CSRF-token for sending it through fetch post request in React?

 April 20, 2022     fetch-api, laravel, reactjs     No comments   

Issue

I'm developing web-app using create-react-app and Laravel. create-react-app runs dev project on localhost:3000, whereas laravel backend works on localhost:8080. This is part of my code:

const onSubmit = (e) => {
    e.preventDefault();

    const val = rootRef(formRef); // React ref to form
    
    // form data
    const data = {
        firstName: val('firstName'),
        lastName: val('lastName'),
        facultyId: val('facultyId'),
        departmentId: val('departmentId'),
        courseNo: val('courseNo'),
        phoneNumber: val('phoneNumber'),
        emailInput: val('email'),
        password: val('password')
    }

    const request = {
        method: "POST",
        // mode:   "cors",
        // cache:  "no-cache",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify(data)
    }

    fetch('http://localhost:8080/signup', request)
        .then(res => res.json())
        .then(console.log)
}

So, when I submit the form I'm getting 419 unknown status. I've read laravel docs and found that this happens, because POST request doesn't contain csrf token. Laradocs says (for axios):

If you are not using this library, you will need to manually configure this behavior for your application

But how to make same thing for create-react-app based project?


Solution

Put this in your main blade view

<meta name="csrf-token" content="{{ csrf_token() }}">

Then, capture the csrf token value via JS And pass it in the headers

const token = document.head.querySelector('meta[name="csrf-token"]').content;

headers: {
  "Content-Type": "application/json",
  "X-CSRF-TOKEN": token
},


Answered By - Luis Montoya
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing