无法在 Laravel 测试 API 路由中执行 POST 请求

Can't perform POST requests in Laravel test for API routes

我正在为我的 Laravel 应用程序编写功能测试,我在其中对我的服务执行一些请求。

在尝试测试我的 API 时,所有 GET 请求都工作正常,但所有 POST 请求 return 此响应:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="refresh" content="0;url='http://localhost'" />

        <title>Redirecting to http://localhost</title>
    </head>
    <body>

我的测试代码如下所示:

$this->post('api/my/route')->dump();

我的 api 路线如下所示:

Route::prefix('my')->group(function() {
    Route::post('/route', function() {
        return 'ok';
    });

是否有任何中间件等。在创建这样的请求之前,我可能需要 change/deactivate?

这些请求在使用 web.php 路由时工作正常

您将需要 return 一个 json 回复。 json 方法会自动将 Content-Type header 设置为 application/json,并使用 json_encode [=] 将给定数组转换为 JSON 18=]函数:

所以你确实应该 return 数据如下。

Route::prefix('my')->group(function() {
    Route::post('/route', function() {
        return response()->json(['message'=>'ok']);
    });

@Deepesh Thapa所述,你应该return JSON。

并且在您的测试中,您应该像这样添加 postJson

$this->postJson('api/my/route')

通过 docs.

祝你好运!