【问题标题】:React Native fetch getting an Empty array when making POST request to Laravel Api向 Laravel Api 发出 POST 请求时,React Native 获取一个空数组
【发布时间】:2020-06-07 09:01:21
【问题描述】:

我正在开发一个用于自学的项目,该项目在后端使用 laravel,并在前端运行 react native。我已经为我的应用程序实现了登录和注册屏幕。现在我正在尝试通过它的 api 路由将它连接到我的 laravel 服务器。我第一次遇到 CORS 问题,所以我通过制作一个新的中间件并编辑 kernel.php 文件来解决这个问题。

CORS Issue with React app and Laravel API

现在我尝试先用 get request 运行一些测试,我在 react 中的提交函数是

handleSubmit = async() => {
const email  = this.state.email
const pass = this.state.password

const proxyurl = "https://cors-anywhere.herokuapp.com/";
/*TEST FOR GET REQUEST */
let response = await fetch(`http://mobileprediction/api/user?email=${email}&pass=${pass}`, {
  headers: {
     "Content-Type" : "application/json",
     "Accept" : "application/json"
   },

})


let result = await response.json()
console.log(result)
}

我在 laravel 路由中的 api.php 文件是

Route::get("/user", function (Request $request) {
  return $request;
});

它给出了所需的输出,但是当我用同样的方式测试一个 post 请求时,无论如何我都会得到一个空数组,我无法弄清楚问题是什么

我的 react native 应用中的 handlesubmit 函数是

handleSubmit = async() => {
const email  = this.state.email
const pass = this.state.password


/*TEST FOR POST REQUEST */
 let response = await fetch(`http://mobileprediction/api/user`, {
   method: "POST",
   header : {
     "Content-Type" : "application/json",
     "Accept" : "application/json"
   },
   body : JSON.stringify({
     emailid : email,
     password : pass
   }),
 })

let result = await response.json()
console.log(result)
}

而laravel中的api.php文件是

Route::get("/user", function (Request $request) {
  return $request;
});

Route::post("/user", function(Request $request) {
  return $request;
});

【问题讨论】:

    标签: laravel react-native fetch laravel-6 laravel-api


    【解决方案1】:

    我认为您将路由写入web.php,因为您的 API 可以将端点写入api.php

    尝试在app/Http/Kenrel.php 中评论VerifyCsrfToken 中间件。 它存在安全问题,但您可以在学习步骤中进行。

    [ https://laravel.com/docs/6.x/routing ] [在此链接中搜索 CSRF]

    任何指向 Web 路由文件中定义的 POST、PUT 或 DELETE 路由的路由都应包含 CSRF 令牌字段。

    【讨论】:

    • 已经尝试在VerifyCsrfToken中间件中添加路由,没用。我认为对于移动应用程序,需要 api.php 进行身份验证,然后接受发布请求。
    • @FurrukhJamal 在 VerifyCsrfToken 中间件中添加路由不是我的答案。如果你的路由在 routes/web.php 中,我说评论/删除这个中间件。或者你可以在 routes/api.web 中有你的路线(更好的方式)。在 web.php laravel 有 CSRF 问题
    • 也试过了,甚至将我的帖子逻辑转移到 web.php 但仍然得到一个空数组作为响应
    【解决方案2】:

    所以我的理解是,从 react native 的 fetch 请求中,它不仅仅是发送输入,而是一个页面,其正文具有 json 格式的键值。所以我无法访问服务器中的数据

    $request->param 
    

    或与

    request("param")
    

    您可以使用

    获取 json 格式的字符串
    $request->json()->all()
    

    但我仍然无法获得个人价值观

    对我来说,工作是获取所有内容,然后使用

    访问这些值
    $postInput = file_get_contents('php://input');
       $data = json_decode($postInput, true);
       return ["email" => $data["emailid"] ];
    

    【讨论】:

      猜你喜欢
      • 2016-11-27
      • 2020-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-11
      • 1970-01-01
      • 2020-08-17
      • 2019-02-12
      相关资源
      最近更新 更多