Axios Post with formData does not work with Laravel - laravel

I'm using Axios v0.27.1 for ajax, but does not work to post the files and data to Laravel Controller. When I use $request->all() in controller. It will return a blank [] array. Any ideas for this case?
$('#submitForm7').on('click', function(event) {
event.preventDefault();
var formData = new FormData();
formData.append('file', $('#form7Excel').prop('files')[0]);
let config = {
headers: {
'Content-Type': 'multipart/form-data'
}
, responseType: 'blob'
}
axios
.post('/pdf/generateForm7', formData, config)
.then(resp => {
//success callback
if (resp.status == 200) {
}
})
.catch(error => {
})
.finally(() => {})
})

Can access file using
$request->file('file');
and your all Request data (without file data) You can access using
$request->all();

Related

Laravel Sanctum + Vue Auth

I have an API that is secured using Laravel Sanctum. In the front-end I managed to login with sanctum and a new bearer token is issued. So far so good but how can I store the token (without Vuex) to local storage and how I tell axios to use that token for any future requests ?
My code is as follows:
// AuthController.php
public function login(Request $request)
{
$fields = $request->validate([
'email' => 'required|string',
'password' => 'required|string'
]);
$user = User::where('email', $fields['email'])->first();
$token = $user->createToken('login_token')->plainTextToken;
if (!$user || !Hash::check($fields['password'], $user->password)) {
return response([
'message' => 'Invalid Login Credentials'
], 401);
}
$response = [
'user' => $user,
'token' => $token
];
return response($response, 201);
}
// Login.vue
export default {
methods: {
handleLogin() {
axios.get("/sanctum/csrf-cookie").then(response => {
axios.post("/api/login", this.formData).then(response => {
if (response.status === 201) {
this.$router.push({ path: "/" });
}
console.log(response);
});
});
}
},
data: function() {
return {
logo: logo,
formData: {
email: "",
password: ""
}
};
}
};
The login works fine, it is returning the expected results but I don't know how to store the generated token and how to send it to any future axios requests.
Thanks.
*** UPDATE ***
Ok so I figured it out how to send the headers and I'm doing it like so:
axios
.get("/api/expenses/", {
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + "6|cnuOY69grhJiZzxEHoU74PapFkkcJeqbf3UiKx8z"
}
})
.then(response => (this.expenses = response.data.data));
}
The only remaining bit to this is how can I store the token to the local storage because right now, for testing purposes I hard coded the token.
In your Login.vue script
methods:{
loginUser(){
axios.post('/login',this.form).then(response =>{
localStorage.setItem('token', response.data.token) //store them from response
this.alerts = true
this.$router.push({ name: 'Dashboard'})
}).catch((errors) => {
this.errors = errors.response.data.errors
})
},
}
In your logged in file lets call it Dashboard.vue in <script>,
data(){
return {
drawer: true,
user: {roles: [0]},
token: localStorage.getItem('token'), //get your local storage data
isLoading: true,
}
},
methods: {
getUser(){
axios.get('/user').then(response => {
this.currentUser = response.data
this.user = this.currentUser.user
}).catch(errors => {
if (errors.response.status === 401) {
localStorage.removeItem('token')
this.$router.push({ name: 'Login'})
}
}).finally(() => {
setTimeout(function () {
this.isLoading = false
}.bind(this), 1000);
})
},
},
created(){
axios.defaults.headers.common['Authorization'] = `Bearer ${this.token}` //include this in your created function
this.getUser()
this.isCreated = true
}
I hope it works well for you
Ok so this is how I sorted this out.
Storing the token in the local storage:
localStorage.setItem("token", response.data.token);
Using the token when sending an axios call to the api:
const token = localStorage.getItem("token");
axios
.get("/api/endpoint/", {
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + token
}
})
.then(response => (this.expenses = response.data));
}

cannot decode json laravel

I am developing a react native app where i have table data to send controller in laravel.Here is my react native code for table data post request to controller
var userToken = await AsyncStorage.getItem("userToken");
fetch('http://xxx.xxx.xxx.xxx/tajroof/public/api/createSales', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
Authorization:`Bearer ${userToken}`,
},
body: JSON.stringify(
this.state.resdata
)
}).then((response) => response.json())
.then((responseJson) => {
console.log(responseJson)
// Alert.alert(responseJson.status);
// this.setState({modalVisible:false})
}).catch((error) => {
alert(error);
});
}
here is my controller with json decode
$data =json_decode($request->getContent(),true);
print_r($data);
foreach ($data as $key => $value) {
echo $value["category_id"] . ", " . $value["pname"] . "<br>";
}
but i am getting response
Array[
Object{
"category_id":1,
"pname":"Potato"
},
Object{
"category_id":2,
"pname":"Oil"
}
]
if i try with another code in laravel controller like this
$data=$request->getContent();
$data=response()->json($data);
then i got response like this
[{"category_id":1,"pname":"potato"},{"category_id":2,"pname":"oil"}]
In both cases i am unable to fetch category id ,pname(product name).Please help ..Your help will appreciate

Fetch in react native doesn't send the post with codeIgniter API

Fetch post is not working with the json api coded with codeIgniter. The get method works but there's issue in post method. The key is not recognized between the react native and code igniter. Any help is appreciated. Thankyou
fetch('http://zzz.com/login', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: 'abc',
}),
})
.then(response => response.json())
.then(responseJson => {
console.log('responseJson', responseJson);
})
.catch((error) => {
console.error('fetchError', error);
});
CodeIgniter controller
public function login()
{
$un = $this->input->post('username'); //why doesn't the key 'username' is working here
echo json_encode($un);
}
CONSOLE LOG:
responseJson false
Updates:
1)Using json_decode, gives error
"fetchError SyntaxError: Unexpected end of JSON input"
public function login()
{
$Data = json_decode(file_get_contents('php://input'), false);
echo $Data;
}
2)Using json_encode gives following outcomes:
responseJson {"username":"abc"}
public function login()
{
$Data = json_encode(file_get_contents('php://input'), false);
echo $Data;
}
Update 1:
1) Using only file_get_contents gives the output as: responseJson {username: "abc"}
public function login()
{
$Data = (file_get_contents('php://input'));
echo $Data;
}
2)using var_dump and json_decode in server code, it gives following error in the app console
public function login()
{
$Data = json_decode(file_get_contents('php://input'), true);
var_dump ($Data);
}
Error:
fetchError SyntaxError: Unexpected token a in JSON at position 0
at parse (<anonymous>)
at tryCallOne (E:\zzz\node_modules\promise\setimmediate\core.js:37)
at E:\zzz\node_modules\promise\setimmediate\core.js:123
at E:\zzz\node_modules\react-native\Libraries\Core\Timers\JSTimers.js:295
at _callTimer (E:\zzz\node_modules\react-native\Libraries\Core\Timers\JSTimers.js:152)
at _callImmediatesPass (E:\zzz\node_modules\react-native\Libraries\Core\Timers\JSTimers.js:200)
at Object.callImmediates (E:\zzz\node_modules\react-native\Libraries\Core\Timers\JSTimers.js:464)
at MessageQueue.__callImmediates (E:\zzz\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:320)
at E:\zzz\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:135
at MessageQueue.__guard (E:\zzz\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:297)
console log the response as following gives the array in app console:
fetch('http://zzz.com/login', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: 'abc',
})
})
.then((response) => console.log('response', response))
Console:
response
Response {type: "default", status: 200, ok: true, statusText: undefined, headers: Headers, …}
headers:Headers {map: {…}}
ok:true
status:200
statusText:undefined
type:"default"
url:"http://zzz.com/login"
_bodyInit:"array(1) {↵ ["username"]=>↵ string(3) "abc"↵}↵"
_bodyText:"array(1) {↵ ["username"]=>↵ string(3) "abc"↵}↵"
__proto__:Object
Try to add same-origin mode like below :
fetch('http://zzz.com/login', {
method: 'POST',
credentials: 'same-origin',
mode: 'same-origin',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: 'abc',
}),
})
.then(response => response.json())
.then(responseJson => {
console.log('responseJson', responseJson);
})
.catch((error) => {
console.error('fetchError', error);
});
From the front end, send the data as a form data (as shown below).
const formData = new FormData();
formData.append("name", "RandomData");
formData.append("operation", "randomOperation");
In your Codeigniter controller, receive it as...
$name = $this->input->post("name");
$operation = $this->input->post("operation");

Empty response from post with formData

In VueJS i am trying to perform a post
let data = new FormData()
data.append('name', 'hey')
fetch('http://homestead.test/api/customers', {
method: 'POST',
headers: {
'Content-type': 'multipart/form-data'
},
body: data
})
.then((response) => response.json())
.then((response) => {
console.log(response)
})
Added a resource route
Route::resource('customers', 'CustomerController');
and return the request
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
return $request->all();
}
And my console.log prints the following
[]
You are calling a then after the fetch's then which does not exists.
You can use arrow functions at then for accessing the response variable you got from the request
let data = new FormData()
data.append('name', 'hey')
fetch('http://homestead.test/api/customers', {
method: 'POST',
headers: {
'Content-type': 'multipart/form-data'
},
body: data
})
.then((response) => {
// now you can access response here
console.log(response)
})
I do not understand why FormData is empty, but all requests with JSON body works.
let data = new FormData()
data.append('name', 'hey')
let json = JSON.stringify(Object.fromEntries(data));;
fetch('http://homestead.test/api/customers', {
method: 'POST',
headers: {
'Content-type': 'application/json'
},
body: data
})
.then((response) => response.json())
.then((response) => {
console.log(response)
})
I think the problem may be with the content header type it should
{
Content-type: 'application/json'
}
And also try to send the data with:
body :JSON.stringify(data)

Vue request fails but does not log errors

I have this add method in my vue script
if (this.edit === false) {
this.link.link = submitEvent.target.elements.link.value;
fetch('products', {
method: 'POST',
body: JSON.stringify(this.link),
headers: {
'content-type': 'application/json'
}
})
.then(res => res.json())
.then(res => { // this does not get executed
this.qrcode.redirect_url = "";
alert('Added');
this.fetchAll()
})
.catch(err => console.log(err.res));
}
}
When I fill the form the request is send and entry is made to the database but I do not get response.
I am using laravel as backend and Add method in Controller returns 200 response after creation.
What could cause it and why console.log(err) does not not display anything?

Resources