2016-04-18 48 views
1

我試圖使用phpunit來測試我的Laravel API,並且我使用$this->call();方法來執行調用並查看它們是否工作正常。通過PhpUnit使用令牌在laravel 5中發送POST請求?

我也是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']); 

但我仍然得到重定向。我錯過了什麼?

回答

2

爲什麼不嘗試這樣的事情?

$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' => 'XMLHttpRequest'

或嘗試laravel-cors包。

+0

我正在嘗試'Authorization'而不是'HTTP_Authorization'。無論如何,我現在也嘗試過,仍然一樣。 '$ response = $ this-> call('POST','users /?token ='。$ this-> token,$ user,[],[],[],['HTTP_Authorization'=>'承載者'。 $ this-> token]);' – Rohan

+0

嘗試使用完整的URI,以防萬一。 – Hoosk

+0

相同。此外,我嘗試了一個測試路線,並轉儲了request() - > header()'來查看所有的頭文件。雖然存在'「content-type」:[「application \/x-www-form-urlencoded」],但無法看到存在的HTTP_Authorization頭。 – Rohan