Reputation: 13811
I am trying to test my Laravel APIs using phpunit and I am using the $this->call();
method to perform calls and see if they are working fine.
I am also JWT for authentication and hence have to pass my token with it. Simple GET requests are easy:
$response = $this->call('GET', 'users?token=' . $this->token);
But when I need to create a new user or any resource for that matter, I am trying to do:
$response = $this->call('POST', 'users/?token=' . $this->token, $user);
But it is giving me a redirect like so:
<!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>
Now when I did some digging, I came across this:
Redirect 302 on Laravel POST request
And the API for the call method looks like so:
$response = $this->call($method, $uri, $parameters, $cookies, $files, $server, $content);
So I tried this:
$response = $this->call('POST', 'users/?token=' . $this->token, $user, [], [], [], ['Content-Type' => 'application/x-www-form-urlencoded']);
But I am still getting a redirect. What am I missing?
Upvotes: 1
Views: 1609
Reputation: 46
Why don't try something like this?
$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);
Update:
You have CORS enabled in Laravel? Maybe this is the reason.
Use the header: 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest'
Or try laravel-cors package.
Upvotes: 2