2

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?

2 Answers 2

7

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
},
Sign up to request clarification or add additional context in comments.

Comments

1

Here is a working example

<meta name="csrf-token" content="{{ csrf_token() }}">
 const token = document.head.querySelector('meta[name="csrf-token"]').content;

 fetch('/url', {
        method: 'post',
        body : JSON.stringify({
            key: 'value'
        }),
         headers: {
             "Content-Type": "application/json",
             "X-CSRF-TOKEN'": token
         },
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.