PHPer
PHPer

Reputation: 664

AJAX Request no response if the user not logged in - Laravel

I have a web app that runs on Laravel 5.5 and I need to create a shopping cart using ajax exclusively (I have reasons).

When the user is logged in, all runs smoothly. When the user is not logged in I get a empty response.

Routes:

Route::post('/shop/add2', 'ShopController@addToCart')->name('add2cart');

ShopController looks something like:

<?php 

    class ShopController extends Controller
    {

      public static function addToCart(){

       $message = "Some message";

       return response()->json(["message"=>$message]);
      }
    }
?>

Jquery is :

var token  = $('[name="_token"]').val();
var var1  = $(this).data('itemcom');
var var2_  = $(this).data('itemvalue');
$.ajax({
      url: '/shop/add2',
      type: 'POST',
      data: {_token: token, identX:var2_, identY:var1 },
      dataType: 'JSON',
      success: function(response) {
        console.log(JSON.stringify(response));
      },
      error  : function(errors){
        console.log(JSON.stringi(errors));
      }
});

I tried everything I could and I get a 419 status code. I know, right?

Upvotes: 1

Views: 613

Answers (2)

andi79h
andi79h

Reputation: 1167

Hmm, I have a strong devaju with code 419... and not a good one. I had to debug like half a day because a missing Csrf token in a route for facebook's webhook. Maybe this is similar in your case?

class VerifyCsrfToken extends Middleware
{
    const FACEBOOK_ROUTE = 'facebook_hook';

    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        self::FACEBOOK_ROUTE,
        self::FACEBOOK_ROUTE . '/*',
        'upload',
        'upload/*',
    ];

The same goes for my upload, which is done by a third party ajax plugin as well.

Cheers

Upvotes: 0

Laerte
Laerte

Reputation: 7073

If you don't mind that this function will be accessible to everyone, you can add a exception to the middleware in the constructor of the Controller:

public function __construct()
{
    $this->middleware('auth', ['except' => ['addToCart']]);
}

Upvotes: 1

Related Questions