topiji
topiji

Reputation: 105

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

I am writing Feature Tests for my Laravel Application, where I perform some requests to my service.

While trying to test my API, all GET requests work fine, but all POST requests return this response:

<!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>

My test code looks like this:

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

and my api routes look like this:

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

Are there any middleware etc. I might need to change/deactivate before creating a request like this?

These requests work fine when using the web.php routes

Upvotes: 2

Views: 1602

Answers (2)

mare96
mare96

Reputation: 3859

As @Deepesh Thapa mentioned, you should return JSON.

And in your test, you should add postJson like this:

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

Go through the docs.

Good luck!

Upvotes: 2

Deepesh Thapa
Deepesh Thapa

Reputation: 1789

You will need to return a json response. The json method will automatically set the Content-Type header to application/json, as well as convert the given array to JSON using the json_encode PHP function:

So you should indeed return data as below.

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

Upvotes: 1

Related Questions