简体   繁体   中英

How to receive JSON POST request in Laravel

I want to POST Fetch to my backend Laravel server from my React-Native mobile app.I dont know wihch parts is missing or what I'm doing wrong.. Here is the fetch :

fetch('http://example.com/react_test', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                name: inputName,
                email: inputEmail,
                phone: inputPhone
            }),
        }).then((response) => response.json())
            .then((responseJson) => {
                alert(JSON.stringify(responseJson))
            }).catch((error) => {
                alert(error);
        });

I receive data in my backend like this with POST route

Route::post('/react_test', 'QuestionController@index');

public function index($request){

        $n = $request->input('name');

        DB::table('admin_panels')->insert(['discord' => $n, 'twitter' => 'anan']);

        return response('helal');

    }

and I get this error :

Symfony \\ Component \\ HttpKernel \\ Exception \\ MethodNotAllowedHttpException No message

First of all you need to ignore verifying csrf field for that route.

In your app/Http/Middleware/VerifyCsrfToken.php

protected $except = [
    '/react_test',
];

Secondly use argument as Request in your index method.

use Illuminate\Http\Request;

public function index(Request $request){

    $n = $request->input('name');

    DB::table('admin_panels')->insert(['discord' => $n, 'twitter' => 'anan']);

    return response('helal');

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM