Vuejs Axios POST request gets HTTP422 error from Laravel backend - laravel

Hi I am using Vuejs in the frontend and Laravel in the backend. The role of Laravel is handling the API only. The frontend and backend are separated, i.e. I am not using Vuejs in Laravel's resource/js folder.
Now I am sending Axios POST request from Vuejs to Laravel. All the form input values are prevalidated using HTML5 required attribute. And when I console.log the request data, it shows all the fields filled.
In Vue file:
const data = {
name: this.name,
gender: this.gender,
mobile_no: this.mobile_no,
image: this.userImage
};
console.log("Request data . . . .", data);
const response = await this.axios
.post(`${this.AppURL}/admin/user/create`, data, {
headers: {
"Content-Type": "multipart/form-data"
}
})
.then(() => {
console.log("Success. . . . ")
alert("Successfully Driver Added");
})
.catch(error => console.log(error));
And in Laravel, the request is passed through some validation. It's a simple validation to check if all the fields are filled.
I am also using JWTAuth package for the authentication, and the token is generated by it.
It's too much code to write them all the way down here. But I am sure you can understand what I mean.
What I am getting as a response is this
POST http://localhost:8000/api/admin/user/create 422 (Unprocessable Entity)
The actual result I am expected to get is either success or some errors that is according to some if conditions in validation or token check.
I tried to figure out where this error might come from. What I think at the moment is this could be due to the absence of csrf_token in the POST request. As I'm sending the request outside Laravel, csrf_token is missing in the form. I am not 100% sure though about this.
So my question is:
How can I include csrf_token in Axios POST request, when I send it from outside Laravel.
If this 422 error is not related with csrf_token, what could be causing this? Any previos experiences like min? and any solutions for this?
Thanks in advance for your help.

Please, modified catch block as #Jack suggested:
.catch(error => {
console.log("ERRRR:: ",error.response.data);
});
Now you can get errors and handle errors in the catch block.

.catch(function (error) {
console.log(error.response.data.errors);
});
please use this code I hope it work's.

I was also facing the same issue, i think it is due to some Headers missing in your Api request from vue.js. here some tips which may helps you to solve this issues.
Make sure that you are protecting your Api Routes or not(by sanctum or something else). If you are protecting , then make make sure that you are sending authentications token in headers.
Second make sure that your request(axios or jwt) should contained valid data, if your are sending images or files etc make sure how can we send them.
First, get request and check in laravel by dd($erquest->all()); if you are geeting data then validate, it is possible that laravel request doesnt contained your sending data..

These errors may be caused due to follow reasons, ensure the following steps are followed.
To connect the local host with the local virtual machine(host).
Here, I'am connecting http://localhost:3001/ to the http://abc.test
Steps to be followed:
We have to allow CORS, placing Access-Control-Allow-Origin:* in header of request may not work. Install a google extension which enables a CORS request.
Make sure the credentials you provide in the request are valid.
Make sure the vagrant has been provisioned. Try vagrant up --provision
this make the localhost connect to db of the homestead.

Just click on the preview tab within network section in the dev tool, you are going to see the actual error message.

Related

Laravel/Vue - Sessions on firefox not working correctly (CSRF token mismatch, session data is null, etc)

I'm working on a project with Laravel and inline vue*. For submitting forms we use axios-calls.
On chrome there is no issue, but in Firefox, with every axios call it gives back a 419 error 'csrf tokens mismatched'.
I googled this issue, and some say adding the CSRF-token to the header. Did that, see below, but it does not work.
axios.defaults.headers.common = {
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
'X-XSRF-TOKEN': decodeURIComponent(this.readCookie('XSRF-TOKEN')),
};
After trying lot's of different answers, I added '*' to the $except array in VerifyCsrfToken.php. (= All my routes will not work with the CSFR-token, not a good practice, but i did this for debug)
The form will submit now. But in the form handling (controller.php), I save some data in the session. In chrome I get the data I need, in Firefox this session data is null.. So I guess the csrf-token stored in the user session is null in firefox. How do I fix this? How do I solve the issue with user-sessions?I also found out that when i send a request with firefox it creates an entire new session/file in storage/framework/sessions, always with a different _token..
I use this in myController.php, to store the data I need in the session:
$request->session()->put('formData', json_encode($data));
$request->session()->save();
TIA!
In .env
App_url=www.site.be
session_domain=
App_name=site
In session.php:
driver => file
lifetime => 120
encrypt => false
secure => false
'http_only' => true
*: We use inline vue-scripts in the blade.php files to submit data.
I tried:
CSRF-token to the header
$req->session()->save()
Changed .env variables around, and in session.php (values above are current)
Changed app_name so it will not have a '.' or '_'
Added _token="{{ csrf_token() }}" to formdata in axios call.
Added "content-type": "application/json" to axios call
Php artisan optimize:clear
Checked permissions on server
I expected it to make the site work, but alas, it does not.
Asked this question on r/laravel and it is solved.
It looks like Firefox isn't sending the session cookie, wich will
cause all the problems you described as a result. Use the browser
developer tools to inspect requests to confirm this. Then, try to
configure Axios to always send cookies, something like
withCredentials: true.
So I added "axios.defaults.withCredentials = true;". And it works! Will keep this here, so others might learn from my mistakes

Laravel api - 405 not allowed shared hosting

I'm new to Laravel and i have the next problem.
I have an API POST route that works properly in the localhost. I send POST requests from POSTMAN:
Route::group(['middleware' => 'api_import'], function () {
Route::get('/products', [ArticlesController::class, 'index']);
Route::post('/products', [ArticlesController::class, 'addOrUpdateArticles']);
Route::post('/categories', [CategoriesController::class, 'addOrUpdateCategories']);
});
However, it will not work on hosting. Hosting is shared, and I get the message:
When json contains a couple of products everything works properly. When json contains a complete table of 3500 products I get this error.
It is possible that there is a redirect on the page. You should confirm this through the network tab in your browser, because any POST request with a redirect is considered a GET request, so an error appears (405 Method Not Allowd)

Why axios delete/patch not working on server but works locally with laravel

I got this code
axios.delete('/replies/' + this.reply.id)
.then((response) => {
flash('Successfully Deleted!', 'success');
}).catch((err) => {
console.log(err)
})
this works perfectly locally, but on server it's not working , not only delete also patch while post works fine locally and on server,
axios.patch('/replies/' + this.reply.id, {
body : this.body
}).then((response) => {
flash('Successfully Updated!', 'success');
}).catch((err) => {
console.log(err)
})
This happens for me in three different website on the same hosting, if the delete/patch request is comming from normal blade it works ok even on server, but when i use axios it only works locally not on the server
Notice : only one of the three projects i added the axios code to it, other projects are from open source projects and no one except me suffers from this, so i have to assume it's not the code, it's the hosting itself, what is missing for me to do ?
Try to add _method: patch to your request.
As suggested in Laravel Routing Docs, in the part of Form Method Spoofing
If you are getting a 403 then you might not have the CSRF token in the request that Laravel uses to verify that a request is coming from your application. On production things become more strict then on local environments.
Have a look at: https://laravel.com/docs/7.x/csrf
I found that the server is not accepting patch and delete http requests, so i changed the apache settings and now it's working fine, another option is that you define the method in data and user axios.post
axios.post(url, {
data: this.data,
__method: 'delete'
})
this works too

How to properly connect Nuxt.js with a laravel backend?

I am starting a new project, Nuxt.js for the frontend and Laravel for the backend.
How can I connect the two?
I have installed a new Nuxt project using create-nuxt-app, and a new laravel project.
As far as I have searched, I figured I need some kind of environment variables.
In my nuxt project, I have added the dotenv package and placed a new .env file in the root of the nuxt project.
And added CORS to my laravel project, as I have been getting an error.
The variables inside are indeed accessible from the project, and im using them
like this:
APP_NAME=TestProjectName
API_URL=http://127.0.0.1:8000
And accessing it like this:
process.env.APP_NAME etc'
To make HTTP calls, I am using the official Axios module of nuxt.js, and to test it i used it in one of the components that came by default.
The backend:
Route::get('/', function () {
return "Hello from Laravel API";
});
and from inside the component:
console.log(process.env.API_URL)//Gives 127.0.0.1:8000
//But this gives undefined
this.$axios.$get(process.env.API_URL).then((response) => {
console.log(response);
});
}
What am I doing wrong here?
I have tried to describe my setup and problem as best as I can. If I overlooked something, please tell me and I will update my question. Thanks.
Taking for granted that visiting https://127.0.0.1:8000/ in your browser you get the expected response, lets see what might be wrong in the front end:
First you should make sure that axios module is initialized correctly. Your nuxt.config.js file should include the following
//inclusion of module
modules: [
'#nuxtjs/axios',
<other modules>,
],
//configuration of module
axios: {
baseURL: process.env.API_URL,
},
Keep in mind that depending on the component's lifecycle, your axios request may be occurring in the client side (after server side rendering), where the address 127.0.0.1 might be invalid. I would suggest that you avoid using 127.0.0.1 or localhost when defining api_uris, and prefer using your local network ip for local testing.
After configuring the axios module as above, you can make requests in your components using just relative api uris:
this.$axios.$get('/').then(response => {
console.log(response)
}).catch(err => {
console.error(err)
})
While testing if this works it is very helpful to open your browser's dev tools > network tab and check the state of the request. If you still don't get the response, the odds are that you'll have more info either from the catch section, or the request status from the dev tools.
Keep us updated!
Nuxt has a routing file stucture to make it easy to set up server side rendering but also to help with maintainability too. This can cause Laravel and Nuxt to fight over the routing, you will need to configure this to get it working correctly.
I'd suggest you use Laravel-Nuxt as a lot of these small problems are solved for you.
https://github.com/cretueusebiu/laravel-nuxt

MethodNotAllowedHttpException with lucadegasperi/oauth2-server-laravel's included AccessTokenFlow POST route

This is my first Laravel project I'm on, and it has been a ton of fun so far.
I'm setting up an OAuth2 server. I have copied the code posted here in to my routes file.
Via this block of code...
Route::post('oauth/access_token', function()
{
return AuthorizationServer::performAccessTokenFlow();
});
I have tried doing http://local.server.com/oauth/access_token and a "MethodNotAllowedHttpException" error.
If there is any other information I could provide that would help you help me, please tell me!
Cheers
If you are typing http://local.server.com/oauth/access_token into the browser URL bar, then you are sending the request:
GET oauth/access_token
However, your route handles a POST request, and since there is no GET route defined, Laravel is responding with MethodNotAllowedHttpException
In order to properly test your route, you will need to send a POST request.

Resources