Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel API Post Returns Login Screen

I have two resource routes that both call the store method on my model.

Route::resource(/calls, 'CallController'); <--- Inside routes/web.php
Route::resource(/v1/calls, 'CallController'); <--- Inside routes/api.php

When I post to https://example.com/calls, the model is correctly persisted to the database and the appropriate response is returned.

When I post to https://example.com/api/v1/calls, I get a 201 response and the login screen is returned.

Why am I getting two different responses? At first I thought it might be the CRSF token, but I am using Laravel 5.6. As far as I know, neither of these routes are behind any authentication.

I have attached the request headers of the successful call not using the API

:authority: example.com
:method: POST
:path: /calls
:scheme: https
accept: application/json, text/javascript, */*; q=0.01
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
cache-control: no-cache
content-length: 214
content-type: application/x-www-form-urlencoded; charset=UTF-8
cookie: XSRF-TOKEN=eyJpdiI6IkZlRzFxSERKbVplWFNrdEhaSUJyN3c9PSIsInZhbHVlIjoiaHRab3o4b2Q3d3h4WVNFNnRUYmw2Qm5yN0gwczJ6eDR6aFFIXC9wNmVvTzFvckE2Wks5djRjcjJDTkttRDd6VHB4V1IzK3Z4RldTZkF4Vkl2WlNLdmpBPT0iLCJtYWMiOiJiYTJlZjY1ZWM4MWNjYmIyZjllMTMyNjkzMWY5YzU1YzhlMDUxMjU0MmI0YWQ5ZDMyZmQ3ZjZiY2NlZjA5MDQ5In0%3D; test_session=eyJpdiI6ImgwbG1wd0U2N3gxN1djNURCY3JNdUE9PSIsInZhbHVlIjoiYWF1c3JJXC9MZ0ZJVjhoSDNQS0ZtbGlGXC91UkZXeEZOenE2MVJTQXlUZFFwZVlPUHNKS3pieEtmc2hFM3EzNnB6SFVLVHZUQVlGTEdub1wvaXBhVmhncHc9PSIsIm1hYyI6ImQzOGYwMWIxZGM2ODM1NjZhYjAyMjdiNGM4YjI2NDA3NTY3YzVlNzc3YWMyNjIwOTY3YTlkNTY0YWI0YTk3MTkifQ%3D%3D
origin: https://example.com
pragma: no-cache
referer: https://example.com/web
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36
x-csrf-token: OyGKA35SMQJINoANVje94osmQOSNQAZT7MCx4LQA
x-requested-with: XMLHttpRequest
like image 742
Neve12ende12 Avatar asked Oct 27 '25 09:10

Neve12ende12


1 Answers

You need to add the following header to your API request:

Accept: application/json       // <-- this indicates how you'd like to receive the response
/** and optionally: */
Content-type: application/json // <-- this indicates the data format that you are sending

This will tell Laravel to use the api guard, because by default Laravel uses the web one.

like image 100
Kenny Horna Avatar answered Oct 29 '25 00:10

Kenny Horna



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!