I am looking to post multiple url to my server using http post method, i can not seems to find a solution to that.
Is it possible to do that with Axios http client or just simply making an Http Post Call ?
Axios Post request
axios({
method: 'post',
url: 'www.myurl.com',
dataType: "json",
contentType: "application/json",
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Bearer HkwWTBXekkrR0MybFlnUmc9');
},
success: function (data) {
console.log(data);
});
AJAX call method that i have tried that fails
Multiple url in same ajax call?
var urls = ["http://www.test.com/users/", "http://www.example.com/users/", "http://www.test.org/users/"]
$.each(urls, function(index, value) {
$.ajax({
url: value,
type: "POST",
data: (
answer_service: answer, expertise_service: expertise, email_service: email),
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Bearer 5YCwxCbWEvHIHO_nRvURIG5hP7s');
},
dataType: "json",
contentType: "application/json",
success: function (data) {
console.log(data);
Axios has an axios.all method which can handle multiple requests. (https://github.com/axios/axios)
const urls = [
"https://www.test.com/users/",
"https://www.example.com/users/",
"https://www.test.org/users/"
];
const generateRequests = () => urls.map( url => axios.get(url));
axios.all(generateRequests())
.then(axios.spread(function (acct, perms) {
// All requests are now complete
console.log('done', acct, perms);
}));
Few more examples:
https://www.storyblok.com/tp/how-to-send-multiple-requests-using-axios
https://github.com/sahat/hackathon-starter/blob/master/controllers/api.js#L37
Related
My question is Node uses request.write to send JSON post request and jquery's AJAX uses the 'data' field. Do I understand it right?
Here my node.js
const apiToken = "eae5819bd5e14803a1abff8141c36ee6";
const contentJSON = JSON.stringify({
'contestId': "0ac3ac99-0509-456a-8ff6-9f193048c4f3",
'contesttype': "OverUnder",
'direction': "moon",
'wager': "0.001"
});
const https = require('https');
const options = {
hostname: 'beta.hxro.io',
port: 443,
path: '/hxroapi/api/ContestEntry/add-contest-entry',
method: 'POST',
headers: {
'Content-Type':'application/json',
'Ocp-Apim-Subscription-Key': 'agh383j89dh93ij9',
}
}
const req = https.request(options, (res) => {
res.on('data', (d) => {
console.log(JSON.parse(d));
});
});
req.on('error', (error) => {
console.error(error);
});
req.write(contentJSON);
req.end();
This is what I think in jQuery it will look like:
contentJSON = {
contestId: contestId,
userId: "AB",
contesttype: "OverUnder",
direction: "moon",
wager: "0.00005"
};
console.log(contentJSON);
$.ajax({
type: "POST",
url: "https://beta.hxro.io/hxroapi/api/ContestEntry/add-contest-entry",
data: JSON.stringify(contentJSON),
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: {
"Content-Type": "application/json",
"Ocp-Apim-Subscription-Key": "sa77euhe83ji40ie"
},
success: function(data) {
console.log(data);
},
failure: function(errMsg) {
alert(errMsg);
}
});
Node's one works but not the jquery. JS solutions are welcome.
When I make an RxJS Ajax call request I set the headers of request, but how can i get Cookie of RxJS Ajax Response?
import { ajax } from 'rxjs/ajax';
ajax({
url: "some url",
body: {
parameter1: "abc",
parameter2: "def"
},
headers: {
"Content-Type": "application/json",
"Cache-Control": "no-cache"
},
method: 'POST',
responseType: 'json'
})
.subscribe(
payLoad => {
console.log(payLoad);
console.log(payLoad.headers);
},
error => console.log(error),
() => console.log( 'done' )
);
You can set withCredentials: true to set appropriate XHR option so that cookies & headers will be treated differently.
And then, after request is done, access cookie using document.cookie or some other library
something like:
ajax("https://some-url").subscribe(
res => {
console.log(document.cookie);
}
);
I need to send a rest request to a web server, I am using this code :
var getData = function(...) {
return $http({
method: "PUT",
url: getStatistics,
headers: {
'loginId': ...,
'token': ...,
'Content-Type': 'application/x-www-form-urlencoded',
},
data: {"...":"...","...":"...","...":"...","...":"...",
"...":"....","....":"...",
"datefrom":"2017-01-01","dateto":"2017-10-20"}
}).then(function(result){
var dataString = JSON.stringify(result.data);
alert(result.data);
return result.data;
});
};
The problem is that I am receiving error 400 bad request, What should I do?
The request works on Postman With this structure
https://i.stack.imgur.com/BBrwF.jpg
https://i.stack.imgur.com/NbQuO.jpg
Should it be a problem of how Am I passing the data object ?
That's how I implemented the $httpParamSerializerJQLike, it it Correct?
app.factory('statistics', function($http,$httpParamSerializerJQLike) {
var getData = function(loginId,token,id,dataInizio,dataFine,periodo,selezione) {
// Angular $http() and then() both return promises themselves
var data = '{"datefrom":"2017-01-01","dateto":"2017-10-20"}';
alert(data);
return $http({
method: "PUT",
url: getStatistics,
headers: {
'loginId': loginId,
'token': token,
'Content-Type': 'application/x-www-form-urlencoded',
},
data: { 'data': $httpParamSerializerJQLike(data)}
}).then(function(result){
var dataString = JSON.stringify(result.data);
alert(result.data);
return result.data;
});
};
return { getData: getData };
});
you're sending an x-www-form-urlencoded body, but it contains a single parameter named data, containing JSON.
You thus need
data: $httpParamSerializerJQLike({data: angular.toJson(data)})
I have to make an async call which uses cookie to get bearer token which has to be passed to make actual ajax call for the resource.
And I have written the following code which works awesome and get's me the result.
Can I use ajaxPrefilter or beforeSend options to get the tokens, I tried to find documentation for ajaxPrefilter which says it accepts a function, but does that waits for that function to be finished before making actual call?
Token retrieval function
function getTokenUsingCookieAsync() {
return new Promise(function (resolve, reject) {
$.ajax('/retrieve-token').done(function (result) {
resolve(result.token);
}).fail(function (message) {
reject(message);
});
});
}
Actual execute function:
function execute(url, method, data) {
var deferred = $.Deferred();
getTokenUsingCookieAsync().then(function (response) {
var reqSettings = {
async: true,
url: url,
cache: false,
type: method,
headers: {
Authorization: 'Bearer '+ response,
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: data ? JSON.stringify(data) : null
};
$.ajax(reqSettings).done(function (result) {
deferred.resolve(result);
}).fail(function (message) {
deferred.reject(message);
});
}).catch(function (message) {
deferred.reject(message);
});
return deferred.promise();
}
So the following pseudo code is possible or not?
$.ajaxPrefilter((options) => {
$.ajax('/retrieve-token').done((result) => {
options.headers = {
Authorization: `Bearer ${result}`
};
});
});
$.ajax('actual-url')
.done(whatever);
I have 2 requests
$.ajax({
type: "POST",
url: "http://sandbox.gasvisor.com:9988/uaa/oauth/token",
data: "grant_type=client_credentials",
headers: { 'Content-Type': 'application/x-www-form-urlencoded',
'Authorization':'Basic SVRXRV9XRUJfQVBQOml0d2VfY2xpZW50' },
success:function(data){
console.log(data);
getData(data.access_token);
}
})
function getData(acess_token){
$.ajax({
type: "GET",
url: "http://sandbox.gasvisor.com/api/v2/gobjects/search/withinRadius?longitude=24.711117&latitude=48.922633&radius=10",
headers: {
'Authorization':'bearer'+acess_token },
success:function(data){
console.log(data);
}
})
}
They return json from server. I need to get data from Json file to my Angular listing. Pls help me.
Here is a simple example for one of your call:
$http({
method: 'POST',
url: 'http://sandbox.gasvisor.com:9988/uaa/oauth/token',
data: 'grant_type=client_credentials',
headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization':'Basic SVRXRV9XRUJfQVBQOml0d2VfY2xpZW50' },
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
$scope.response = response;
}, function errorCallback(err) {
// called asynchronously if an error occurs
// or server returns response with an error status.
$scope.error = err;
});