Axios is repeating prefix route in Laravel - laravel

I don't know why when I try to make a petition, axios didn't get the route well.
The error:
Then here's the error, I have a operations.js where I make an axios post to the route operation_calls as you see below, but I don't know why axios isn't getting only the url I wrote, it is getting repeating twice.
const operacionLlamadasApp = new Vue({
el: '.crud-operation-calls',
methods:{
storeOperations(){
// as you see I only write it once and I expect to go there
axios.post('operation_calls', {
param1 : param1,
param2 : param1
})
.then(response =>{
})
}
}
});
When in the browser I'm in this url, creating a new row: http://my-domain/operation_calls/create and click on the save button I expect to go to operation_calls store route but I get this error:
Request URL: http://my-domain/operation_calls/operation_calls
Request Method: POST
Status Code: 405 Method Not Allowed
As you see, the prefix is repeated when I only typed it once.
Also I have this error in the response apart of my browser console:
The POST method is not supported for this route. Supported methods: PUT
I'm using:
Laravel 6.*
Axios: ^0.19
I've created routes like this:
Route::group(['prefix' => 'operation_calls'], function(){
Route::put('/{id}','OperationsCallController#update');
Route::resource('/','OperationsCallController', ['names' => [
'create' => 'operations.create']
]);
});
Basically, I have this routes:
GET|HEAD operation_calls index
POST operation_calls store
GET|HEAD operation_calls/create create
PUT operation_calls/{id} update
Here's the way I make the post method, in my blade.php I have this form:
<div class="crud-operation-calls">
<form role="form" method="POST" v-on:submit.prevent="storeOperations()">
#csrf
...
</form>
</div>
Also, I made a axios post only like this:
axios.post('', {
param1 : param1,
param2 : param1
})
.then(response =>{
})
And this is what I get:
Request URL: http://my-domain/operation_calls/create
Request Method: POST
Status Code: 405 Method Not Allowed
I don't know what I'm doing wrong. It's like is passing the prefix of the current page. But I think axios just should go to the route I write in it's parameter. Why is it changing?
What I tried:
Clearing route cache of laravel: php artisan route:cache
Clearing cache of the browser
My .env file it's fine APP_URL=http://my-domain/ because it works with other urls.

Simply prefix your route with a / like this
axios.post('/operation_calls', {
param1 : param1,
param2 : param1
})
.then(response =>{
})

I think you are directly posting from http://my-domain/operation_calls/create. So it assumes as relative URL appends extra URI there. Try
axios.post('{{ route('operation_calls.store') }}', {
param1 : param1,
param2 : param1
})
.then(response =>{
})
Also, remove that <form> because we are posting via VUE, no need of extra FORM for posting. Use can change to <form> to <div>. Don't forget to pass CSRF token too in Vue post()

Related

Send POST request to Laravel web.php route

I have a simple Vue app in which I am sending POST request with options (table filtering variables) to the back-end. I want to be able to destructure the object and debug it in my TestController in Laravel 8, so I want to send the options to web.php via URL, not to api.php. Since options is an object, I cannot just drop it in the URL.
Ultimately I want to be able to preview my Laravel respond in browser, so I know it returns correct data from server.
So how can I achieve this?
in Vue FormComponent <form #submit="formSubmit"> and script
function formSubmit(e) {
e.preventDefault();
let currentObj = this;
axios.post('/formSubmit', {
name: this.name,
description: this.description
}).then(function(response) {
currentObj.output = response.data;
console.log(currentObj);
}).catch(function(error) {
currentObj.output = error;
});
}
Firstable, create POST route for your request. Then just make POST request to this route url and put your POST params (your object) to request body. You can use Axios as example
let filterOptions = {...};
axios.post(url, filterOptions).then().catch();
UPD And response for your request you can see in browser developer console on network tab

Axios Get request return html not data SPA

need some help. I'm trying to fetch data from my db using axios. My backend is Laravel. I have a 200 status http request but it returns the whole html not the data I'm expecting.
Here is my code for route
Route::get('/home', 'PostController#ajaxCall');
Route::post('/home', 'PostController#store');
Route::get('/{any?}', function () {
return view('welcome');
});
Here is my code for Home.vue for Axios request
export default {
components: {addForm},
data () {
return{
posts:[]
}
},
created() {
axios.get('/home').then(response => this.posts = response.data);
}
}
For my controller
public function ajaxCall(){
return response(Post::all());
}
It looks like you get to the ajaxCall() method by using the route '/home', but with axios, you are hitting "/" which returns a view called Welcome. Maybe you need to change the path you use in axios to '/home'?
It might be late but maybe someone else is looking for the solution
I was also facing this in SPA using laravel and VUE.
Route::get('/{any}', 'SinglePageController#index')->where('any', '.*');
SPA has this route, so whenever you write any other get route your app will redirect you to the home page, to avoid this either move this route at the end of your web.php
or write your other routes in api.php file.
In my case i solved it by changing the GET method to POST method.
Try that. It might help

Can't use fetch api in laravel, redirect login page

I'm trying to use fetch api with laravel, but the request goes to the login url, not the given url.
for example;
route
//also this route group has auth and admin middlewares (checks user is authenticated and is admin)
Route::delete("media/delete/{id}", ["as" => "admin.posts.media.delete", "uses" => "AdminController#deletePostMedia"]);
ajax
fetch("../../media/delete/" + id, {
method: "DELETE",
headers: new Headers({
"X-CSRF-TOKEN": document.head.querySelector("[name=csrf-token]").content
})
})
it gives me the below error:
DELETE http://commerce.test/login 405 (Method Not Allowed)
as you can see above, the request goes to login url, not given url..
How can I fix this?
Laravel by default includes axios for ajax requests and it's very easy to use, have a look here.
In your example you'd write something like this:
axios.delete('/media/delete/' + id)
.then(response => {
console.log(response.data);
})
.catch(error=> {
console.log(error);
});

VueJS: how to get route url?

I am working in laravel with Vue, and I can't get route url.
For example there is route localhost:8000/chat/3 and I need to get 3 in route
I tried in app.js to write in
data: {
userId: this.$route.params
}
and then in
created() {
console.log(this.userId);
}
So i can send ajax request to that route. But it returns TypeError: this.$route is undefined. I tried also with other things than params but it allways show this error

Laravel vs. Ajax: incorrect routing

I'm trying to populate "position" dropdown based on "department". The Ajax call is triggered on change event of the "department" dropdown.
The problem is that the Ajax call can't reach the correct route:
with url: 'ajax/get-position' - the url is: localhost/public/join/ajax/get-position?dept_id=5
with url: '/ajax/get-position' - the url is: localhost/ajax/get-position?dept_id=5
Both of the URLs are wrong and I have no idea why. Especially this /join/ in the first point is a mystery to me. The correct URL should be localhost/public/ajax/get-position?dept_id=5. I believe there's some kind of a conflict in the routing, however I'm not sure where.
The Ajax call is made on localhost/public/join/editor page.
JS:
...
...
$.ajax({
url: 'ajax/get-position',
data: {
dept_id: value
},
type: 'GET',
dataType : 'json',
success: function(json) {
//
},
error: function(xhr, status, errorThrown) {
//
}
});
...
...
Routes:
Route::get('join/editor',
array(
'uses' => 'DefaultController#showEditorRegistration',
'as' => 'editorRegistration'
)
);
Route::post('join/editor',
array(
'uses' => 'DefaultController#createEditor',
'as' => 'createEditor'
)
);
// ROUTE FOR AJAX CALL
Route::get('ajax/get-position',
array(
'uses' => 'DefaultController#getPositionsByDepartment',
)
);
Any ideas?
EDIT:
The JavaScript is in an external file. If I put the JS directly in blade.php view and use URL::route('routename') as Ajax url value - all works fine. However, simply using url: ajax/get-position - does not. Crazy world.
I'm not completely sure, but based on our conversation about the details of your project I think the issue has to do with the location of your document root. the public directory should never show up in any of your laravel project's urls.
I created a demo project to demonstrate a simple interaction with Laravel and Ajax. It's a vanilla laravel project with slight alterations to the hello view.
Checkout the project, navigate into the public folder, and use the following command to spin up an ad-hoc phpserver:
php -S localhost:8002
You can then go to the url http://localhost:8002 to get to the homepage.
If you inspect the link on the home page and look at the url that is generated with the URL facade for the route tester. The URL doesn't include the public directory:
http://localhost:8003/tester
You can also look at the ajax setup and see that you can use the tester route as well.
$('#getbutton').click( function (){
$.ajax({
url: 'tester'
}).complete(function (a){
alert(a.responseText);
}).error(function (a){
console.log(a);
});
});
Using either the link or the ajax call on button click will hit the tester route in the routes file:
Route::get('tester',[ 'as' => 'tester', 'uses' => function (){
return 'worked';
}]);
The link can hit the route via the route name tester assigned in the routes file, and the ajax request can hit the route from the query string.
The routes in your project look ok and using ajax/get-position as your url in the ajax call shouldn't be an issue.
Give this project a try. Even if the issue isn't a webroot one, hopefully it will help you figure out where your issue is coming from.

Resources