Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

178
Views
Laravel 5.4 Api Route 401

I built a new laravel 5.4 project.

I tried to do the steps below in my api route, but somehow they do not work.

In my app.js file I have this ajax call:

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
    }
});
$.ajax({
    url: 'api/postStream',
    type: 'post',
    data: { imgData: imgData },
    success:function(data) {
        console.log('success');
    }
});

My Api Route looks like this:

Route::group(['middleware' => 'auth:api'], function()
{
    Route::post('postStream', ['as' => 'image', 'uses' => 'ApiController@postStream']);
});

And my controller:

public function postStream(Request $request)
{
    $imgData = $request->imgData;
    ...
}

But I get this error in my chrome dev console:

POST http://localhost/app/public/api/postStream 401 (Unauthorized)

And in the network tools this:

{error: "Unauthenticated."}
error
:
"Unauthenticated."

I guess I am somewhat not authentificated, but I do not know how to make that happen this way.

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

It doesn't work because your route is protected by auth:api, which returns 401 unauthorized. The only way to go through auth:api is to send your authentication token with every single request

var token = <?php json_encode(Auth::user()->api_token); ?>; //if you are using api_token

$.ajax({
    url: 'api/postStream',
    headers: {
        'Authorization':'Bearer ' + token,
    },
    type: 'post',
    ...
});

The way you get your token is entirely up to you. You could use Passport or simply the easiest solution which is adding api_token to your users table.

If you are going for the cheapest solution, you can follow this post: https://gistlog.co/JacobBennett/090369fbab0b31130b51

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!