php - Laravel 5.4 Api Route 401 -
i built new laravel 5.4 project.
i tried steps below in api route, somehow not work.
in app.js file have 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 this:
route::group(['middleware' => 'auth:api'], function() { route::post('poststream', ['as' => 'image', 'uses' => 'apicontroller@poststream']); });
and controller:
public function poststream(request $request) { $imgdata = $request->imgdata; ... }
but error in chrome dev console:
post http://localhost/app/public/api/poststream 401 (unauthorized)
and in network tools this:
{error: "unauthenticated."} error : "unauthenticated."
i guess not authentificated, not know how make happen way.
it doesn't work because route protected auth:api
, returns 401 unauthorized
. way go through auth:api
send authentication token every single request
var token = <?php json_encode(auth::user()->api_token); ?>; //if using api_token $.ajax({ url: 'api/poststream', headers: { 'authorization':'bearer ' + token, }, type: 'post', ... });
the way token entirely you. use passport or easiest solution adding api_token users table.
if going cheapest solution, can follow post: https://gistlog.co/jacobbennett/090369fbab0b31130b51
Comments
Post a Comment