创建 API 并测试它时,我收到以下关于 Route:Register inside Postman 的错误消息:
错误:套接字挂起
但是我在源代码中看不到任何错误。 这可能是什么原因?
http://localhost:8000/api/register
api.php
<?php
use App\Http\Controllers\ProductController;
use App\Http\Controllers\AuthController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
// Public Routes
Route::post('/register', [AuthController::class, 'register']);
Route::get('/products', [ProductController::class, 'index']);
Route::get('/products/search/{name}', [ProductController::class, 'search']);
Route::get('/products/{$id}', [ProductController::class, 'show($id)']);
// Protected Routes
Route::group(['middleware' => ['auth:sanctum']], function() {
Route::post('/products', [ProductController::class, 'store']);
Route::put('/products/{$id}', [ProductController::class, 'update ']);
Route::delete('/products/{$id}', [ProductController::class, 'delete']);
});
//
// Route::post('/products', [ProductController::class, 'store']);
// ;
AuthController.php
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Hash;
class AuthController extends Controller
{
public function register(Request $request) {
$fields = $request->validate([
'name' => 'required|string',
'email' => 'required|string|unique:users,email',
'password' => 'required|string|confirmed'
]);
$user = User::create([
'name' => $fields['name'],
'email' => $fields['email'],
'password' => bcrypt($fields['password'])
]);
$token = $user->createToken('myapptoken')->plainTextToken;
$response = [
'user' => $user,
'token' => $token
];
return response($response, 201);
}
}
php artisan 服务正在运行 当我取消选中主体 @postman 中的键时,我得到:
{ "message": "The name field is required. (and 2 more errors)", "errors": { "name": [ "The name field is required." ], "email": [ "The email field is required." ], "password": [ "The password field is required." ] } }
您的代码运行完美。 从头开始重新创建单个邮递员请求并删除 cookie。