Vue request fails but does not log errors - laravel-5

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?

Related

Why put request is not working using axios to make a laravel api request?

Here is a request from my Vue component:
submit() {
axios
.put(`/api/posts/${this.slug}`, this.fields, {
headers: { "content-type": "multipart/form-data" },
})
.then((res) => {
// some logic
})
.catch((error) => {
// some logic
});
}
api.php
Route::group(['prefix' => 'posts', 'middleware' => 'auth:sanctum'], function () {
Route::put('/{post:slug}', [PostController::class, 'update']);
});
put method doesn't work. I get the following error xhr.js:220 PUT http://127.0.0.1:8000/api/posts/test-title-updated-33 422 (Unprocessable Content) but when I replace put with post everything works as expected. I don't understand why put is not working.
Because HTTP PUT is not recognized by HTML standard.
You need to add POST type of method only but for update you can add a small flag with POST request for a PUT/PATCH type of operation.
axios.post(`/api/posts/${this.slug}`, { // <== use axios.post
data: this.fields,
_method: 'patch' // <== add this field
})

Axios Post with formData does not work with 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();

Call a function just after ajax call is sent

I have to show a message "Request for execution sent" after the ajax call is made but before the response is received in axios.
axios
.post('executeTask', {
id,
status,
name
})
.then(response => {
})
.catch(error => {
});
Just show message before handling your promise:
var promise = axios
.post('executeTask', {
id,
status,
name
});
// show message here
promise.then(response => {
})
.catch(error => {
});

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)

Resources