how to return server response from axios - async-await

I've looked at some of the other posts on this and it seems I need to apply 'await' I'm just not sure how to modify the following to do that
function sendData(url,emailPass){
let bodyFormData = new FormData()
for (const [key, value] of Object.entries(emailPass)) {
console.log(key,value)
bodyFormData.append(key,value)
}
axios({
method: 'POST',
url: url,
data: bodyFormData,
headers: {'Content-Type': 'multipart/form-data'}
})
.then(function (response){
return response.data
})
.catch(function(response){
return response
})
}

You should modify the function to return the promise from axios, which returns the response data.
function sendData(url,emailPass){
let bodyFormData = new FormData()
for (const [key, value] of Object.entries(emailPass)) {
console.log(key,value)
bodyFormData.append(key,value)
}
return axios({
method: 'POST',
url: url,
data: bodyFormData,
headers: {'Content-Type': 'multipart/form-data'}
})
.then(function (response){
return response.data
})
.catch(function(response){
return response
})
}
If you want to use async/await you can do
async function sendData(url,emailPass){
let bodyFormData = new FormData()
for (const [key, value] of Object.entries(emailPass)) {
console.log(key,value)
bodyFormData.append(key,value)
}
try{
const response = await axios({
method: 'POST',
url: url,
data: bodyFormData,
headers: {'Content-Type': 'multipart/form-data'}
});
return response.data;
}catch(e){
return e.response.data;
}
}

Related

react axios 401 unauthorized and sometimes 403

I'm building a react native app post requesting laravel php api. it works on postman but not on Axios. Do you know how can i solve? I can't post a form data
I tried other forms sending post request of Axios. but none of them is solution
axios({
method: 'post',
url: 'URL',
params: {
"api_token": token,
"name": "talha"
},
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data'
}
}).then(response => alert(response)).catch(err => console.warn(err))
-----
const serverURL = "URL";
const http = axios.create({
timeout: 1000,
baseURL: serverURL,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
withCredentials: false,
cache: false,
dataType: "jsonp"
});
data is a formdata
await http.post("/passengers", data, config)
.then(Response => alert(Response.data))
.catch(error => console.warn("hata", error))
-----
axios.post( 'URL',
data,
{
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data'
}
}
).then(function(){
alert('SUCCESS!!');
})
.catch(function(){
alert('FAILURE!!');
});
postman script:
https://pastebin.ubuntu.com/p/vS54dytpCQ/
You can use my API helper function for batter development.
import axios from 'axios';
import AsyncStorage from '#react-native-community/async-storage';
const api = async (url, method, body) => {
/**
* config object for fetch
*/
const config = {
method: 'get',
baseURL: 'BASEURL WILL BE HERE',
url,
headers: {
'Content-type': 'application/json',
authorization: await AsyncStorage.getItem('auth_token'),
},
};
if (method) {
config.method = method;
}
if (body) {
config.data = body;
}
let response;
try {
response = await axios(config);
return {...response.data};
} catch (e) {
throw new Error(e.message);
}
};
export default api;
Then use this function
import api from 'filpath';
const functionName = async () => {
try{
const res = await api('/passengers', 'POST' posData);
console.log(res.data);
} catch(e){
alert('FAILURE!!')
}
}
Note: Save the auth token to AsyncStorage when user login.

Modify ajax response that gets passed to .done()

this.getFullAddress(id).done(function(data) {
// need to have both the response (data) and the id
});
getFullAddress(id) {
var response = $.ajax({
url: 'http://whatever.com'
}); // modify this (add id)
return response;
}
Does anyone have an idea how to accomplish this ?
Ok, found it:
getFullAddress(id) {
$.ajaxSetup({
dataFilter: function (response) {
response = JSON.parse(response);
response['id'] = id;
response = JSON.stringify(response);
return response;
}
});
return $.ajax({
url: 'http://whatever.com'
});
}

Angular Datatables use source object

With Angular Datatables I want to pre-load a JSON object with Ajax so that I can re-use the object elsewhere without doing another ajax request.
But how do I load this object into the datatable?
.controller('ResponsiveDatatableCtrl', function ($scope, $rootScope, DTOptionsBuilder, DTColumnBuilder, apiserv, $filter, $state, $http) {
$scope.dataLoading2 = true;
var vm = this;
var data = "?db="+ $rootScope.globals.currentUser.agents[$rootScope.globals.currentDB].db_name;
var url = apiserv+"api.files.php"+data;
var headers = {'Content-Type': 'application/x-www-form-urlencoded'};
$http({
method: 'POST',
url: url,
headers: headers,
})
.success(function (response) {
$rootScope.globals.files = response;
$scope.dataLoading2 = false;
//console.log($rootScope.globals.files);
});
vm.dtOptions = DTOptionsBuilder.fromFnPromise($rootScope.globals.files)
.withPaginationType('full_numbers')
.withBootstrap()
.withOption('responsive', true);
})
Ok I have attempted the following and it seems to call my code under success but then the table doesn't update?
vm.dtOptions = DTOptionsBuilder.newOptions().withOption('ajax', {
url: url,
type: 'POST',
headers: headers,
data: function(data, dtInstance) {
},
success: function(response) {
$rootScope.globals.files = response;
}
})
.withPaginationType('full_numbers')
.withBootstrap()
.withOption('responsive', true);

I don't receive data from formdata in my sails.js server

I have this ajax request:
this.sendApiRequestWithFile = function (method) {
var formData = new FormData();
formData.append("name", "my name");
data_ajax = {
url: "http://localhost:1337/" + method,
method: "PUT",
data: formData,
headers: {
'Cache-Control': 'no-cache',
'Content-Type': 'multipart/form-data; boundary=----',
}
}
return $http(data_ajax).success(function(data, status, headers, config) {
return data;
}).error(function(data, status, headers, config) {
return data;
});
}
And my server is in sails.js so I catch parameters like this: req.body and it doesn't work. I try req.params.all() and doesn't work too.
I hope the following code should work. If you try to access the uploaded file from server, use req.file("file_name")
var fd = new FormData()
fd.append("name", "name value")
$.ajax({
url: "/url",
type: "POST",
data: fd,
processData: false,
contentType: false,
success: function(response) {
console.log("Success : " + response);
},
error: function(jqXHR, textStatus, errorMessage) {
console.log(errorMessage); // Optional
}
});
});

How to use ajaxmanager with jquery ajax request?

I'm trying to use the ajax blockmanager plugin to manage my jquery ajax requests, but I'm not sure how to implement it...
// Follow button click event
$('#loginBtn').click(function () {
var that = this;
var request = {
'username': $('#txtUsername').val(),
'password': $('#txtPassword').val()
};
var params = $.toJSON(request);
ajaxManager.add($.ajax({
type: "POST",
url: "ajax/Login.aspx/Login",
data: params,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (result.d === true) {
window.location = "dashboard.aspx";
}
else {
$('#errorMessage').slideDown();
}
}
}));
I know it's a bit outdated question... But if anyone comes across this issue:
You are passing the already created/started request as a parameter to the manager.
You should only pass its options. The request will be created and handled by the manager.
ajaxManager.add({
type: "POST",
url: "ajax/Login.aspx/Login",
data: params,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (result.d === true) {
window.location = "dashboard.aspx";
}
else {
$('#errorMessage').slideDown();
}
}
});
Do you have ajaxManager instantiated?
//create an ajaxmanager named cacheQueue
var ajaxManager = $.manageAjax.create('cacheQueue', {
queue: true,
cacheResponse: true
});
You first create the manager
this.ajaxManager = $.manageAjax.create("aiapi", {
queue: true,
cacheResponse: true,
maxRequests: 3,
abort: this.abortCallback
});
where the queue of calls is active, max concurrent requests are 3, and the caching is enabled. The common abortCallback is like
this.abortCallback = function (response) {
Logger.log("APIManager.abortCallback " + Utils.toString(response));
};
It's convenient to add the common ajaxSetup setup like
$.ajaxSetup({
cache: true,
timeout: 10 * 1000
});
Here you can see the response timeout in msec set to 10 sec.
You then do a GET like
this.DoGet = function (url, method, timeout) {
return new Promise((resolve, reject) => {
var options = {
type: 'GET',
url: url + method,
contentType: "application/json",
timeout: (15 * 1000) // sets timeout to 60 seconds
};
if (timeout) options.timeout = timeout;
const errorCallback = function (error) {
console.error(error);
return reject(error);
};
const successCallback = function (data) {
return resolve(data);
};
const completeCallback = function (data) {
return resolve(data);
};
options.error = errorCallback;
options.success = successCallback;
//options.complete= completeCallback;
$.manageAjax.add("default-queue", options);
/*$.ajax(options)
.done(function (data) {
return resolve(data);
})
.fail(function (error) {
console.error(error);
return reject(error);
})
.always(function () {
// called after done or fail
});*/
});
You can see in the comment the version without the ajax manager. And it the same way to POST is like
this.DoPost = function (url, method, body, timeout) {
try {
body = JSON.stringify(body);
} catch (error) {
console.error(body);
return reject(error);
}
return new Promise((resolve, reject) => {
var options = {
type: 'POST',
url: url + method,
data: body,
contentType: "application/json",
dataType: 'json',
timeout: (15 * 1000) // sets timeout to 60 seconds
};
if (timeout) options.timeout = timeout;
const errorCallback = function (error) {
console.error(error);
return reject(error);
};
const successCallback = function (data) {
return resolve(data);
};
options.error = errorCallback;
options.success = successCallback;
$.manageAjax.add("default-queue", options);
/*$.ajax(options)
.done(function (data) {
return resolve(data);
})
.fail(function (error) {
console.error(error);
return reject(error);
})
.always(function () {
// called after done or fail
});*/
});
}//DoPost
The important thing here is the name of the ajax queue when adding a new GET / POST request via the api
$.manageAjax.add("default-queue", options);
This means basically that you can have one or more queues, that improves your requests parallelism.

Resources