status: 405, statusText: "Method Not Allowed", in axios .post laravel - laravel

i am trying to do axios.post method for sending the messages . But i am getting this error repeatedly.
my script looks like this
sendMsg(){
if(this.msgFrom){
axios.post('messages/sendMessage/',{
conID:this.conID,
msg:this.msgFrom
})
.then(response => {
console.log('saved successfully');
})
.catch(function (error) {
console.log(error.response);
});
}
}
Route looks like this
Route::post('/messages/sendMessage','Messages#sendmsg');
and controller looks like this
public function sendmsg(Request $request){
echo $request->msg;
}
and i am getting the error code 405,method not allowed , any solutions please.

I am going to make an assumption:
Your route is currently in the default api.php file
So you may need to modify your URL in the axios request to include the /api/:
/api/messages/sendMessage

Related

No response data from Laravel API using Axios

I am setting up authentication using Laravel (Laravel Framework version 5.8.4) as a REST API, but when I make a post request using Axios, I get back an empty string.
Here is my code in Laravel: "login" endpoint in my main controller:
class MainController extends Controller
{
public function login(Request $request){
$data = [
'message' => 'yo'
];
return Response::json($data, 200);
}
}
Here is my Axios code (from Vue.js method):
methods: {
submitRegistration: function() {
axios.post('http://envelope-api.test/api/auth/login', {
name: this.form.name,
email: this.form.email,
password: this.form.password,
password_confirmation: this.form.password_confirmation
})
.then(function (response) {
console.log("here's the response")
console.log(response);
})
.catch(function (error) {
console.log(error);
});
},
}
Here is the response from Postman (it works!)
{
"message": "yo"
}
Here is the response from my axios request in console (empty string, where's the data?) :
{data: "", status: 200, statusText: "OK", headers: {…}, config: {…}, …}
To get data from axios you should use response.data, not just response.
Edit: Try to respond with the helper.
response()->json($data);
I've got this figured out. Thanks for your help.
I had this chrome extension installed to allow CORS (Cross Origin Resource Sharing) so I could do API requests from localhost (apparently, not needed for Postman?).
I turned it off and installed it locally on Laravel using this post (answer from naabster)
After I installed this way, it worked regularly.

TypeError: Cannot read property 'status' of undefined when receiving errors from Laravel validation

I'm trying to validate a form via AJAX using Axios with vue.
axios.post('api/registro', this.sede)
.then(response => {
this.$emit('cerrar')
})
.catch(err => {
console.log(err)
})
The error comes from the catch part, as it's coming from a Laravel validator. The response from the server is 422 and it contains a JSON with a message and the errors the server is sending.
Everything works fine if I dont try to log the error.
The problem was coming from me using interceptors in axios, I wasn't returning the errors in the interceptors properly, so nothing was coming into the catch function.
This is what I had:
axios.interceptors.response.use(null, function (error) {
// some logic
});
And this is how it should've been:
axios.interceptors.response.use(null, function (error) {
// some logic
return Promise.reject(error);
});
Thank you all so much for your help.
You can just check for errors like so:
if(err.response.data.errors){
this.errors = err.response.data.errors;
}
this.errors would be an array you can loop through using v-for to display it

Axios get request to Laravel endpoint from next.js

I have the following request to my laravel endpoint:
axios.get('http://localhost:8000/auth/login', {})
.then(function (response) {
console.log(response);
return {};
})
.catch(function (error) {
return {}
});
And my laravel endpoint set up as:
public function index() {
var_dump('login called.');die;
return response()->json(
[],
200
);
}
I Started my nextjs server (port 3000) and laravel server(8000), and when i browse to localhost:8000/auth/login in my browser I see "login called". however when I do that axios call, I get a status 200ok but no response data.
Request URL:http://localhost:8000/auth/login
Request Method:GET
Status Code:200 OK
Remote Address:127.0.0.1:8000
Referrer Policy:no-referrer-when-downgrade
Any idea what I am doing wrong?
Nothing is wrong with your code you are getting the response correctly, you see "login called" because you are accessing from a browser, therefore a browser has the cappability to render the html and you can see that.
But that axios call expects some json in return.
If you tweak the response a bit:
public function index() {
return response()->json(
['data' =>'Log in called'],
200
);
}
and if you twak axios response a bit
axios.get('http://localhost:8000/auth/login', {})
.then(function (response) {
console.log(response.data);
return {};
})
.catch(function (error) {
return {}
});
Inspect element open console and you will see 'Log in called'

Catching errors with axios

I can not catch the error response with axios. How to do that?
I use something like:
axios
.post(...)
.then(response => {
console.log('Success: ', response)
}).catch(error => {
console.log('Error: ', error)
})
I see that the result of ajax request has 400 status code and the response body looks like {someField:["This field may not be blank"]} (Django backend). That's ok, I'm ready to process these errors in the catch handler.
But they go to the success handler instead. Why so? I see the following output in the console:
Success: Error: Request failed with status code 400
at createError (createError.js:16)
at settle (settle.js:18)
at XMLHttpRequest.handleLoad (xhr.js:77)
The success handler receives axios error object as the result. Why that may be and what to do next? This error object does not contain any usefull information.
UPD. Actually, the error object does contain the useful information, it contains the response object inside. So we can use:
axios
.post(...)
.then(response => {
if (response && response.response) {
console.log('This is also an error', response.response.status)
} else {
console.log('Success: ', response)
}
}).catch(error => {
console.log('Error: ', error)
})
But that looks super ugly.
The axios version is axios#0.16.2.
That's the big project, but I can not find any axios customizations.
Use Axios interceptors for the response. Check which status you want to force to fail as error so they go through the catch path whenever you receive said status code.
axios.interceptors.response.use(function (response) {
if (response.status === 400) {
return Promise.reject(response);
}
return response;
}, function (error) {
// Do something with response error
return Promise.reject(error);
});
If you are not receiving the expected status code, you might change the way you check the response in the interceptor. You can check any of the elements that Axios response is structured.
axios.interceptors.response.use(function (response) {
if (response.statusText !== 'OK') {
return Promise.reject(response);
}
return response;
}, function (error) {
// Do something with response error
return Promise.reject(error);
});

Can't access laravel response from ajax library

// Edit: Hm...this is an firebug bug in firefox. On chrome it works...
I'm using Laravel 5.3 with Vue 2.0 and the axios ajax library.
Here is a test controller, where i return a response from laravel:
public function testMethod() {
return response('this is an error', 500);
}
Here is my ajax call:
http(`fetch-data`).then(response => {
const data = response.data;
console.log(data);
}).catch(error => {
console.log(error); // <- This doens't work, he show my nothing
alert(error);
});
The problem is, i need the error message which is returned from laravel into my client catch. But if i console.log them, he show me nothing. If i alert the error, he gives me the following message: Error: Request failed with status code 500.
Why can't i access something like error.statusCode, error.statusMessage?
Try
return response()->json('this is an error', 500);

Resources