【问题标题】:POST request in laravel 5 with token via PhpUnit?通过 PhpUnit 在 laravel 5 中使用令牌发布请求?
【发布时间】:2016-08-10 05:01:42
【问题描述】:

我正在尝试使用 phpunit 测试我的 Laravel API,并且我正在使用 $this->call(); 方法来执行调用并查看它们是否工作正常。

我也是用于身份验证的 JWT,因此必须通过它传递我的令牌。简单的 GET 请求很简单:

$response = $this->call('GET', 'users?token=' . $this->token);

但是当我需要为此创建新用户或任何资源时,我正在尝试这样做:

$response = $this->call('POST', 'users/?token=' . $this->token, $user);

但它给了我这样的重定向:

<!DOCTYPE html>\n
<html>\n
    <head>\n
        <meta charset="UTF-8" />\n
        <meta http-equiv="refresh" content="1;url=http://localhost" />\n
\n
        <title>Redirecting to http://localhost</title>\n
    </head>\n
    <body>\n
        Redirecting to <a href="http://localhost">http://localhost</a>.\n
    </body>\n
</html>

现在当我进行一些挖掘时,我发现了这个:

Redirect 302 on Laravel POST request

调用方法的 API 如下所示:

$response = $this->call($method, $uri, $parameters, $cookies, $files, $server, $content);

所以我尝试了这个:

$response = $this->call('POST', 'users/?token=' . $this->token, $user, [], [], [], ['Content-Type' => 'application/x-www-form-urlencoded']);

但我仍然收到重定向。我错过了什么?

【问题讨论】:

    标签: php laravel laravel-5 phpunit forms


    【解决方案1】:

    为什么不尝试这样的事情呢?

    $token = ‘your token’;
    $method = ‘POST’;
    $params = [];
    $response = $this->call($method,'http://api.api.app/api/',
        $params,[],[],['HTTP_Authorization' => 'Bearer ' . $token],[]);
    
    $this->response = $response;
    $this->seeStatusCode(200);
    

    更新:

    你在 Laravel 中启用了 CORS 吗?也许这就是原因。

    使用标题:'HTTP_X_REQUESTED_WITH' =&gt; 'XMLHttpRequest'

    或者试试laravel-cors 包。

    【讨论】:

    • 我尝试使用Authorization 而不是HTTP_Authorization。不管怎样,我现在也试过了,还是一样。 $response = $this-&gt;call('POST', 'users/?token=' . $this-&gt;token, $user, [], [], [], ['HTTP_Authorization' =&gt; 'Bearer ' . $this-&gt;token]);
    • 尝试使用完整的 URI,以防万一。
    • 相同。此外,我尝试了一条测试路线并转储request()-&gt;header() 以查看所有存在的标头。尽管"content-type":["application\/x-www-form-urlencoded"] 存在,但看不到HTTP_Authorization 标头。
    • 我的错,我在最后一个数组中传递它而不是倒数第二个。但我仍然在重定向那里。唯一改变的是请求现在具有标头。
    • 您在严格模式下使用 dingo?也许你还需要两个标题:Accept : application/x.visitapeldoorn.v1+jsonContent-Type : application/json
    猜你喜欢
    • 1970-01-01
    • 2017-07-15
    • 2017-11-15
    • 1970-01-01
    • 2017-10-21
    • 2020-08-18
    • 1970-01-01
    • 2015-11-13
    • 1970-01-01
    相关资源
    最近更新 更多