【发布时间】: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.log或laravel-{date}.log)以查看确切的错误消息。 -
你能不能也给我们看看模型课。 p.s.当你使用
create方法时,你不需要使用save(),它会自己保存
标签: php android laravel react-native