0
votes

I'm trying to send data with ajax (using axios for that) through an api to my controller.
First of all my routes file (/routes/api.php):

Route::post('/booking/request', 'BookingController@sendMail');

I want to send data to this route, so here is my request for that:

var bookingUrl = baseUrl + 'api/booking/request';

axios.post(bookingUrl, {
    name: "username",
    amount: 2
});

And after that, I just want to log this data to see if it got to my controller (app/Http/Controllers/BookingController):

class BookingController extends Controller
{
    public function sendMail(Request $request)
    {
        Log::info('data: ' . $request->name);

    }
}

This doesn't work at all. I just get an error "404 Not Found". I also tried this request with Postman, but same results. Since I can't get more information about what exactly isn't working, I can't fix it. Can someone get me on the right path here?

Edit: So the actual problem was the baseUrl. There was a wrong link behind, so it couldn't work.

1
What is bookingUrl set to? Check php artisan routes:list to make sure it matches. - aynber
Sorry, I just edited my post. bookingUrl is set to baseUrl + 'api/booking/request'. And php artisan routes:list is showing an entry for my route POST | api/booking/request | App\Http\Controllers\BookingController@sendMail | api - kk_
I'm not sure if this will work, but try public function sendMail(Request $request) for the definition, and inside Log::info($request->name); - aynber
I think your attempt is the right way for that part, but it still doesn't work. I also think I don't even get to the controller. The mistake must be somwhere before that. - kk_

1 Answers

2
votes

axios.post is just a post request, not an API specific request.
Put you route declaration in routes/web.php file

//web.php
// now the url for post request will be /booking/request
Route::post('/booking/request', 'BookingController@sendMail');

and in js

//JS
var bookingUrl = baseUrl + 'booking/request';

axios.post(bookingUrl, {
    name: "username",
    amount: 2
});

If you still need api prefix, add api in route declaration

Route::post('/api/booking/request', 'BookingController@sendMail');

// or

Route::group(['prefix'=>'api'], function(){
    Route::post('/booking/request', 'BookingController@sendMail');
});