【问题标题】:post method is not working in laravel 8 with react native for androidpost 方法在 laravel 8 中无法使用 react native for android
【发布时间】:2022-01-19 16:58:47
【问题描述】:

我是 laravel 的新手,我正在使用 laravel 后端和 react native for android,并尝试使用 post 方法将数据从 react native 发送到 laravel,但它不起作用。 这是帖子的控制器。

   <?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Post;

class PostController extends Controller
{
    //
    public function store(Request $request) {
       $post =  Post::create([
       'title' => $request->title,
       'description' => $request->description,
       ]);
       $post->save();
     return response()->json([
      'message' => 'stored post sucessfully',   
     ],201);
    }
}

这是 api.php 中用于添加帖子的 api

Route::post('savePost', [PostController::class, 'store']);

我正在像这样在前端使用这个 api

const data = {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      title: 'First Post',
      description: 'this is my first post',
    }),
  };

const post = async () => {
 await fetch('http://10.0.2.2:8000/api/savePost', data)
      .then(res => console.log('res', res.json()))
      .catch(error => console.log(error));
  };

它正在返回此响应

 {"_bodyBlob": {"_data": {"__collector": [Object], "blobId": "7cef9594-5824-40a5-8186-38f04f5a2f00", "offset": 0, "size": 14036}}, "_bodyInit": {"_data": {"__collector": [Object], "blobId": "7cef9594-5824-40a5-8186-38f04f5a2f00", "offset": 0, "size": 14036}}, "bodyUsed": false, "headers": {"map": {"access-control-allow-origin": "*", "cache-control": "no-cache, private", "connection": "close", "content-type": "application/json", "date": "Thu, 16 Dec 2021 15:34:44 GMT, Thu, 16 Dec 2021 15:34:44 GMT", "host": "10.0.2.2:8000", "x-powered-by": "PHP/7.4.3", "x-ratelimit-limit": "60", "x-ratelimit-remaining": "59"}}, "ok": false, "status": 500, "statusText": "", "type": "default", "url": "http://10.0.2.2:8000/api/savePost"}

提前感谢您的帮助。

【问题讨论】:

  • 看起来您遇到了 HTTP 500 错误:"status": 500,;您需要检查您的日志(storage/framework/logs/laravel.loglaravel-{date}.log)以查看确切的错误消息。
  • 你能不能也给我们看看模型课。 p.s.当你使用create方法时,你不需要使用save(),它会自己保存

标签: php android laravel react-native


【解决方案1】:

我忘记在后期模型中进行批量分配。应该是这样的。


namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;
    protected $guarded = ['id'];
    public $timestamps = false;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-27
    • 2017-06-17
    • 1970-01-01
    • 2018-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多