简体   繁体   中英

API: Ajax post in Laravel - 403 (Forbidden)

I'm getting 403 forbidden during ajax call. This is happen only if the ajax is on app.js . If I remove from app.js and put to index.blade.php , is working perfectly.

How can I make it working also on my app.js ? I've searched a lot, and found I needed to add this

$.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } });

before the ajax, but is still not working..

controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class API extends Controller
{
    public function getSomething(Request $r)
    {
        $r->validate([
            'user' => 'required'
        ]);

        $data = DB::table('posts')->orderBy('id', 'desc')->get();



        return $data;
    }
}

web.php

Route::group(['prefix' => 'api'], function(){
    Route::post('getSomething', 'API@getSomething');
});

index.blade.php

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
<meta name="csrf-token" content="{{ csrf_token() }}" />

.... some of my content ....

<script src="{{ asset('assets/js/app.js') }}"></script>

app.js

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

$.ajax({
    url: '{{ url("api/getSomething") }}', 
    type: 'POST',
    data: {
        user: '1',
        _token: '{{ csrf_token() }}',
        _testThisAjax: true
    },
    success: function (c) {
        console.log(c);                                         
    },
    error: function(e)
    {
        console.log(e);
    }

});

Since {{ url() }} helper method will not work in app.js file so you have to set url in ajax

Your ajax should be like this if you put this in app.js

$.ajax({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    },
    url: '/api/getSomething', 
    type: "POST",
    data: {
             user: '1',
             _testThisAjax: true
    },
    success: function (c) {
        console.log(c);                                         
    },
    error: function(e)
    {
       console.log(e);
    }
});

Note: use either ajax headers for csrf or in data like this:

 data: {_token: $('meta[name="csrf-token"]').attr('content') , 'key' : 'value'}

FOR MORE: https://laravel.com/docs/8.x/csrf

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM