【问题标题】:How to receive JSON POST request in Laravel如何在 Laravel 中接收 JSON POST 请求
【发布时间】:2018-10-04 02:40:28
【问题描述】:

我想从我的 React-Native 移动应用程序将 Fetch POST 到我的后端 Laravel 服务器。我不知道缺少哪些部分或我做错了什么。这是 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);
        });

我通过 POST 路由在后端接收数据

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

    }

我得到了这个错误:

Symfony\组件\HttpKernel\异常\ MethodNotAllowedHttpException 无消息

【问题讨论】:

  • 我没有看到上面配置的任何cross origin resource sharing。根据您对I want to post from my react native app to my laravel app 的描述,这是一项要求。
  • 我怎样才能正确添加它们,也许把它写成答案,如果它可以工作,我可以接受它作为答案
  • 我按照你说的检查并添加到 Header 'Access-Control-Allow-Origin':'', 'Content-Type': 'multipart/form-data' ,现在它没有给出任何错误但一段时间后它给出了网络失败请求错误

标签: json laravel request fetch


【解决方案1】:

首先,您需要忽略验证该路由的 csrf 字段。

在你的 app/Http/Middleware/VerifyCsrfToken.php

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

第二次在你的索引方法中使用参数作为请求。

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

}

【讨论】:

  • 好的,我会检查这些并告诉你:)谢谢!
  • 哇哦,成功了!!!太感谢了!所以当我需要使用 POST 请求时,我应该这样做吗?
  • 我一直在努力,想问你。您认为忽略验证 csrf 令牌会导致一些安全问题吗?
  • @Berke 是的,忽略 csrf 令牌可能会导致一些安全问题。来自任何未知来源的请求也被接受。你必须小心。
  • 我只是不明白他们如何找到我使用的网址?
猜你喜欢
  • 2011-04-14
  • 2012-02-03
  • 1970-01-01
  • 2016-06-12
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
  • 2016-03-01
  • 2015-09-15
相关资源
最近更新 更多