Laravel 5.4 Api Route 401 - php

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.

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

Related

OpenCart 3 - AJAX Query is not working (Invalid token session)

I try to make POST-request to method of admin controller using AJAX (from admin part). My JS code:
<script>
$(".remove-request-btn").on('click', function () {
let request_id = $(this).data('request-id');
let confirm_result = confirm('Are you sure you want to delete this request?');
if (confirm_result) {
$.ajax({
url: 'index.php?route=extension/x_feedback/settings/removeRequest&token={{ token }}',
method: 'post',
dataType: 'json',
data: {request_id: 11},
success: function(data) {
if (data.status === 'ok') {
location.reload();
}
},
error: function () {
alert('Error');
}
});
}
});
</script>
My method:
public function removeRequest()
{
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode(
[
'status' => 'ok'
]
));
}
I expect json in the response but get following:
I tried to add admin into the url like '/admin/index.php?route=extension/x_feedback/button/feedbackRequest&token={{ token }}'
But it doesn't help. Can you help me please what I'm doing wrong? Thank you!
1-please add bellow code into controller method
$data['token'] = $this->session->data['user_token'];
2- use javascript into .twig file - not external js file.
In OC3 is used user_token instead token
so you must use this url:
url: 'index.php?route=extension/x_feedback/settings/removeRequest&user_token={{ user_token }}',
And do not forget declare user_token in the corresponding controller file:
$data['user_token'] = $this->session->data['user_token'];

Getting Message Unauthenticated While Sending Data to Database Table Using Laravel Authentiation and Ajax

I create an API using Laravel 5.8 API Authentication (Passport) saving data with postman getting generated token it works. But when I send it to ajax it gives a this message
({message: "Unauthenticated."})
My Route is
Route::group(['middleware' => 'auth:api'], function(){
Route::resource('r-camera', 'API\RearcamerasController');
});
````````
````````
My ajax code is
<script>
$(document).ready(function(){
$('#btn-add').click(function(e){
e.preventDefault();
/*Ajax Request Header setup*/
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#btn-add').html('Sending..');
/* Submit form data using ajax*/
$.ajax({
url: "http://localhost:8000/api/r-camera",
method: 'post',
data: $('#frmAddTask').serialize(),
success: function(response){
//------------------------
$('#btn-add').html('Submit');
$('#res_message').show();
$('#res_message').html(response.msg);
$('#msg_div').removeClass('d-none');
document.getElementById("frmAddTask").reset();
setTimeout(function(){
$('#res_message').hide();
$('#msg_div').hide();
},10000);
//--------------------------
}});
});
});
</script>
to run API on postman use this toke and it's run
Authorization
enter image description here Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImMzZjQ5ZTA1MzdmMWQxYzI5YjBhNzQ5N2EyZjhiMDVjYjliYzAyMTQ3OWMxMWVkZjEzNDIyNjE1Y2RjNDZmNDVmZjE3MzNmMjZiN2E5MTQxIn0.eyJhdWQiOiIzIiwianRpIjoiYzNmNDllMDUzN2YxZDFjMjliMGE3NDk3YTJmOGIwNWNiOWJjMDIxNDc5YzExZWRmMTM0MjI2MTVjZGM0NmY0NWZmMTczM2YyNmI3YTkxNDEiLCJpYXQiOjE1Nzk4NDgxMjIsIm5iZiI6MTU3OTg0ODEyMiwiZXhwIjoxNjExNDcwNTIyLCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.DS3-YniGiLIr3lTm08DJSd8fdITwYHqW22J9CjjoRFhGAZ4mXpCwb6U1UbJw8yKAQONC93Sj1OxUisg-QfrJ7vUUzFPMCoDDTbS-Hgu5CeRZrLFprYLzm1Eu0WLV9VRAbeQ0P8hPa5tzhbn4oVJ3KMHipjvw3UKse-Noe50LZuktIDZ0KeA1v3PhaaMTCmfXy7S0VXFMSngQbkDVQUWLt8EwcEAGeRGwpvtYz9FzhgSSF5yTz48EvpbqncgLyUo7a0TnbwPYzYR__cyXLeF6FmrrWfaEUD0pkPwZRtalF0bMXPrH-0AKmXJSPQYJxC5SySxf5a5QEVqhzwOlHPTl7iLZkVI9NWMipTmoaf5cSNI4k7gkN8yvYzHbY3C78zFSlEc9zTE9FGX9u4UIIgCEnFAIMwLI20jaUyopFkRMpo5qeU3krZQnLfHaeS5K5MnFEfNarUp4CNvGf-aITxl07KFOSjWk0s5qA9llJCYh7NpdOY2IA1Wq8XxR2qDW7ZwNFmoF83vBxKMjhGEbJokuKJNCmoO591MuOBgzJZt8SJdwn2abrQ96AEL4rJ8HC6pFlMbaHFydwlirwE3NCzIQDsRYr0CjLbvfzGQ4axdq5I-IAo-bcUh2KinuA1XqKEerCrUCNj6oaGKFOAt1VoqZBoRTyLEp8amh7YwG43v_mTE
But when I post a request through ajax from the dashboard
{message: "Unauthenticated."}
Please look attached images for more clear and please help me to solve my issue.
Thanks in advance
You will have to send the Authorization header in your ajax setup as well in your blade file.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
'Authorization': 'Bearer {{ $your_bearer_token }}'
}
});

Laravel AJAX 404 for route

I am working on a Laravel 5.3 solution. I try to call a POST route via AJAX from one of my views to update a set of categories but I get a 404 error everytime I call the route.
Interesting fact: During development I was able to call the route with the JS-code shown below successfully - but since I did some updates to the controller code itself it throws a 404 but no exception.
Here is my controller action:
public function updateTree( Request $request )
{
$data = $request->json()->all();
$result = BlogCategory::rebuildTree($data, false);
if($result > 0) {
return Response::HTTP_OK;
}
return Response::HTTP_NOT_MODIFIED;
}
And here the JS AJAX call:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var updateTree = function (e) {
var list = e.length ? e : $(e.target), output = list.data('output');
console.log(JSON.stringify(list.nestable('serialize')));
$.ajax({
url: '{{ action('BlogCategoryController#updateTree') }}',
type: "POST",
data: JSON.stringify(list.nestable('serialize'))
});
};
$(document).ready(function() {
$('#nestable2').nestable({
group: 1
}).on('change', updateTree);
});
The controller route is bound like that in web.php
Route::post( '/service/blog/categories/updatetree', 'BlogCategoryController#updateTree' );
As you might see, I am using the Laravel NestedSet module from LazyChaser here (https://github.com/lazychaser/laravel-nestedset).
Any input is much appreciated.
Cheers,
Jules
you having opening and closing quotes problem in your ajax url, use like this
$.ajax({
url: '{{ action("BlogCategoryController#updateTree") }}',
type: "POST",
data: JSON.stringify(list.nestable('serialize'))
});

405 (Method Not Allowed) Laravel

I am getting a 405 (Method Not Allowed) in Laravel while trying to delete an item using ajax. Someone please help.
Here is my route
Route::get('/home', 'HomeController#index')->name('home');
Route::post('/destroy', 'PagesController#destroy');
Auth::routes();
Here is my ajax code
function confirmDelete(id){
//alert('Delete post id-'+id);
$.ajax({
type: 'post',
url: 'blogs/destroy',
data: {'id' : id},
dataType: 'json',
cache: false,
success: function(res){
console.log("worked");
alert(res);
}
})
}
Here is my controller
public function destroy (Request $request){
$id = $request->id;
echo json_encode ($id);
// $blog = Blog::findorFail ( $id );
// $blog->delete ();
// return response(['msg'=>'Post deleted',
'status'=>'success']);
// return redirect::to ( '/blogs' )->with ( 'success', 'Post
successfully deleted!' );
}
The reason you're getting this error is because your request URI /blog/destroy doesn't match the route definition /destroy.
Therefore either change the route to
Route::post('/blog/destroy', 'PagesController#destroy');
or change your request
$.ajax({
type: 'post',
url: '/destroy',
// ...
})
Try this for routes->
Route::post('/blog/destroy', 'PagesController#destroy')->(destroyPage);
Try this inside ajax:
$.ajax({
type: 'post',
url:'{{ route('destroyPage') }}',
// ...
})
Got the answer just login to my server and disable the ModSecurity and its works, so, later on, I configure the ModSecurity to not get the 405 methods not allowed error on live server.

Ajax post request in laravel 5 return error 500 (Internal Server Error)

This is my test ajax in laravel 5 (refer below)
$("#try").click(function(){
var url = $(this).attr("data-link");
$.ajax({
url: "test",
type:"POST",
data: { testdata : 'testdatacontent' },
success:function(data){
alert(data);
},error:function(){
alert("error!!!!");
}
}); //end of ajax
});
and the trigger link
Try
and my route
Route::post('test', function()
{
return 'Success! ajax in laravel 5';
});
but it gives me an error when I run the console in google chrome and it doesn't return the expected response "return 'Success! ajax in laravel 5';"
POST http://juliver.laravel.com/test 500 (Internal Server Error)
whats wrong/problem to my code? anything I'm missing?
While this question exists for a while, but no accepted answer is given I'd like to point you towards the solution. Because you're sending with ajax, and presumably still use the CSRF middleware, you need to provide an additional header with your request.
Add a meta-tag to each page (or master layout): <meta name="csrf-token" content="{{ csrf_token() }}">
And add to your javascript-file (or section within the page):
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
See https://laravel.com/docs/master/csrf#csrf-x-csrf-token for more details.
90% of the laravel ajax internal server error is due to missing CSRF token. other reasons can inlucde:
Wrong Request Type (e.g sending post to get)
Wrong data type recived (e.g ajax is expecting JSON and app returns string)
Your .htaccess is misconfigured
Missing Route
Code Error
You can read further about this in details here: https://abbasharoon.me/how-to-fix-laravel-ajax-500-internal-server-error/
I guess this has been solved by now but still the best thing to do here is to send the token with your form
{!! csrf_field() !!}
and then in your ajax
$("#try").click(function(){
var url = $(this).attr("data-link");
$.ajax({
url: "test",
type:"POST",
data: { '_token': token, 'someOtherData': someOtherData },
success:function(data){
alert(data);
},error:function(){
alert("error!!!!");
}
}); //end of ajax
});
You can add your URLs to VerifyCsrfToken.php middleware. The URLs will be excluded from CSRF verification.
protected $except = [
"your url",
"your url/abc"
];
In App\Http\Middleware\VerifyCsrfToken.php you could try updating the file to something like:
class VerifyCsrfToken extends BaseVerifier {
private $openRoutes =
[
...excluded routes
];
public function handle($request, Closure $next)
{
foreach($this->openRoutes as $route)
{
if ($request->is($route))
{
return $next($request);
}
}
return parent::handle($request, $next);
}
};
This allows you to explicitly bypass specific routes that you do not want verified without disabling csrf validation globally.
Laravel 7.X
In bootstrap.js, in axios related code, add:
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = $('meta[name="csrf-token"]').attr('content');
Solved lot of unexplained 500 ajax errors.
Of course it's for those who use axios
By default Laravel comes with CSRF middleware.
You have 2 options:
Send token in you request
Disable CSRF middleware (not recomended): in app\Http\Kernel.php remove VerifyCsrfToken from $middleware array
for me this error cause of different stuff.
i have two ajax call in my page.
first one for save comment and another one for save like.
in my routes.php i had this:
Route::post('posts/show','PostController#save_comment');
Route::post('posts/show','PostController#save_like');
and i got 500 internal server error for my save like ajax call.
so i change second line http request type to PUT and error goes away.
you can use PATCH too.
maybe it helps.
you have to pass the csrf field through ajax please look at the code here
$.ajax({
type: "POST",
url:'{{URL::to("/delete-specialist")}}',
data: {
id: id,
_token: $('#signup-token').val()
},
datatype: 'html',
success: function (response) {
if(response=="deleted"){
$("#"+id).hide();
$("#message").html("successfully deleted");
}
}
});
and you also need to write this input field before this
<input id="signup-token" name="_token" type="hidden" value="{{csrf_token()}}">
still if you do not understand please enjoy this video
https://www.youtube.com/watch?v=ykXL8o0slJA&t=20s
do not forget add "use Illuminate\Http\Request;" on your controller
Short and Simple Solution
e.preventDefault();
var value = $('#id').val();
var id = $('#some_id').val();
url="{{url('office/service/requirement/rule_delete/')}}" +"/"+ id;
console.log(url);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
/* the route pointing to the post function */
url: url,
type: 'DELETE',
/* send the csrf-token and the input to the controller */
data: {message:value},
dataType: 'JSON',
/* remind that 'data' is the response of the AjaxController */
success: function (data) {
console.log(data)
//$('.writeinfo').append(data.msg);
//$('#ruleRow'+id).remove();
}
});
return false;
Using post jquery instead helped me to solve this problem
$.post('url', data, function(response) {
console.log(response);
});
I had same problem. In my case, issue arise because my id field of table (in database) was not set to auto increment. When I set it to auto increment then it started working.

Categories