6

I'm trying to test my API using postman, but when I hit the POST request, it's always throws me to the welcome page. I already set the XSRF token inside but still not working.

This is my api.php routes:

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});
Route::resource('products/{product}/feedbacks', 'FeedbackController');

This is my store method from FeedbackController:

/**
 * Store a newly created resource in storage.
 *
 * @param  \App\Http\Requests\StoreFeedback  $request
 * @return \Illuminate\Http\Response
 */
public function store(Product $product, StoreFeedback $request)
{
   $product->addFeedback(
      $request->validated()
   );

   return response()->json([
      "status" => "success",
      "message" => "Your feedback has been submitted."
   ], 200);
}

Here is my web.php file:


Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

Route::resource('product-categories', 'ProductCategoryController')->parameters([
    'product_category' => 'productCategory'
]);

Route::resource('product-sub-categories', 'ProductSubCategoryController')->parameters([
    'product_sub_category' => 'productCategory'
]);

And here is the screenshot of my postman request: Link to the screenshot

Yura
  • 1,937
  • 2
  • 19
  • 47

6 Answers6

20

POST request always throws the welcome page

The problem lies in your App\Http\Requests\StoreFeedback class.

How?

Cause you're passing the request through the Form Validator. Which invalidates the form request. And that's why passing the request back to the previous URL which becomes the / by default.

Hierarchy below

But, if you want to get the errors, you can simply pass the HEADER Accept:application/json to request HEADER and you'll get the errors.

Reason: ValidationException handled here

ssi-anik
  • 2,998
  • 3
  • 23
  • 52
  • I was just about to post this! from the docs `If validation fails, a redirect response will be generated to send the user back to their previous location.` https://laravel.com/docs/5.7/validation – BizzyBob Mar 03 '19 at 01:44
  • 1
    Since last year, I have been exploring laravel codes. That's unfolding my eyes. :D – ssi-anik Mar 03 '19 at 01:46
  • 1
    Thank you for your answer. I missed an important part of validation – Yura Mar 03 '19 at 01:52
1

I think It's showing the same page because you're using the Route::resource, as said in this Question,

A RESTful resource controller sets up some default routes for you and even names them.

Route::resource('users', 'UsersController');

Gives you these named routes:

Verb          Path                        Action  Route Name
GET           /users                      index   users.index
GET           /users/create               create  users.create
POST          /users                      store   users.store
GET           /users/{user}               show    users.show
GET           /users/{user}/edit          edit    users.edit
PUT|PATCH     /users/{user}               update  users.update
DELETE        /users/{user}               destroy users.destroy

My guess is: you're basically calling the index() function in your FeedbackController over and over again

Change your route to:

Route::post('products/{product}/feedbacks', 'FeedbackController@store');

EDIT change your controller function to:

public function store(Request $request)
{
   dd($request->body); // or the key you send it on the postman
}

And show us what you got

Piazzi
  • 2,490
  • 3
  • 11
  • 25
  • U'uh.. it throws me to the index method instead of store :/ – Yura Mar 03 '19 at 00:53
  • i forgot to point the function, its: 'FeedbackController@store'. I updated my answer. Try again – Piazzi Mar 03 '19 at 00:54
  • I know, I added a `return $request;` too on the controller, and still, nothing happen.. But when I change it to GET, it got fired :/ [link to the screenshot](https://imgur.com/9dB6HMO) – Yura Mar 03 '19 at 01:00
  • This is really strange, put a ```dd($request)``` and see what you got – Piazzi Mar 03 '19 at 01:04
  • It works when I do like this: `Route::post('products/{product}/feedbacks', function () { dd("It does work"); });` – Yura Mar 03 '19 at 01:08
  • You're getting the parameters you're sending? – Piazzi Mar 03 '19 at 01:09
  • yes, I got the parameters. but only if I hardcode it inside a function like this: [link to screenshot](https://imgur.com/f0ae1jB) – Yura Mar 03 '19 at 01:12
  • have you tried any other route (a teste route for example)? This seems like a connection problem, the route never reachs the function. Maybe try to receive just one parameter and print them, just to make sure the route is going to the right place. i Will update my anwser. – Piazzi Mar 03 '19 at 01:23
  • Yes, I did a GET request for it, it reaches the controller and the index method. It's also shows the Product data which is passed from the wildcard. It's weird :/ – Yura Mar 03 '19 at 01:27
  • There is nothing wrong with his code. The problem here is that the form validation failed and he's sent back to the previous page. As he is trying from the postman, there is no previous page, he is sent back to the home page or `/` by default. Don't suggest wrong things. If he passes the `Request` class, that will work. but that's not the case. – ssi-anik Mar 03 '19 at 01:37
1

I'd just found the problem, it was from the app\Http\Requests\StoreFeedback like Mr.ssi-anik said. I don't know why for the boolean validation, when I put true or false, it fails and redirect me to the welcome page.

Instead, I used 0 or 1, it accepts the parameters and working normally.

Yura
  • 1,937
  • 2
  • 19
  • 47
1

As mentioned above this is happening because of the form validator, You can also fix this using middlewares, first create a middleware:

php artisan make:middleware JsonRequestMiddleware

Update the handle method of your middleware

    public function handle(Request $request, Closure $next)
    {
        $request->headers->set("Accept", "application/json");
        return $next($request);
    }

then add this middleware to app/Http/Kernel

protected $middleware = [
        ...
        \App\Http\Middleware\JsonRequestMiddleware::class,
       ...
]
MartinsOnuoha
  • 514
  • 5
  • 9
0

I ran into the same issue but it was my fault. I didn't add the right headers.

Make sure you specify "Content-Type" and "Accept". Both should be set to "application/json". See image below.

Hope this helps.

Postman Headers

Adan A
  • 1
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 12 '22 at 06:46
0

My solution, add failedValidation function in Request

public function failedValidation(Validator $validator) {
    throw new HttpResponseException(response()->json([
        'success'   => false,
        'message'   => 'Validation errors',
        'data'      => $validator->errors()
    ]));
}
Shoukat Mirza
  • 800
  • 9
  • 19