I started writing a program that will automate user actions, by now it's meant to be an easier menu to make faster actions by just sending requests to the official website by clicks on my own page. (something like web-bot but not exactly).
My problem is when i send login request in response i get back user_id, server, session_id etc. And I need to save that session_id to make the other actions.
How can i save this to variable.
All in JavaScript.
I was looking in the internet since yesterday for an answer and i still can't find (or understand) how to get this
I tried
function login(){ fetch('url', { method: 'POST', headers: { //headers }, body: //my Id's }) })
//There's the problem to solve
.then(res => res.text()) .then(data => obj = data) .then(() => console.log(obj)) console.log(body.session_id);
// I even tried the substring but 1. It won't work as I want because There are sometimes //more and less letters. 2. I get and error "Cannot read properties of undefined (reading //'substr')"
`session = obj;
session_id = session.substring(291,30)
console.log(session_id)`
It looks like you're using the text() method on the Response object returned from fetch(), which will give you a string representation of the response.
You probably want to be using the json() method instead, and from that you can get your session_id.
This guide has some more useful information that may help you: https://javascript.info/fetch
Ok it works now with
`async function login(){ let session = await fetch('url', {
//code
}
let result = await session.json();
console.log(result);
session_id = result.data.user.session_id;
user_id = result.data.user.id;`
Related
I am making a chrome extension, and I need to check the availability of multiple websites.
I was thinking that an HTTP request could do it, or loading an img to the server and watching the onLoad event as discussed here : Javascript: Check if server is online?
What method should I use ?
You could use an axios request to each site, check the status code of the response, and then add the website/status code pair to an object.
const serversRunning = {};
for (let server of serverList){
const response = await axios({
url: `{url goes here}`,
method: "GET"
});
serversRunning[server] = response.status;
}
If response code is '200' it's running. I mean, it also depends on what you want to do with that information, but I feel like that would be the easiest that I know of.
or if you just want a list of running servers, change it to:
const serversRunning = [];
for (let server of serverList){
const response = await axios({
url: `{url goes here}`,
method: "GET"
});
if (response.status == '200'){
serversRunning.push(server);
};
}
As the title says, i have a part of my react app that tries to get some data from my database, making a select based on the value I passed to it. So im gonna go ahead and first show the code where i think the problem lies:
So first, this is the function from one of my forms that sends the request to the server, i know code is probably ugly, but i can tell from the console.logs that the parameters im sending are what i intend to send(a string called "licenciaInput"
async handleClickLicencia (event) {
event.preventDefault();
console.log(this.state);
console.log("licenciaInput: "+this.state.licenciaInput);
const datoBuscar = this.state.licenciaInput;
axios.get('http://localhost:3001/atletas/:licencia',this.state)
.then(response =>{
console.log(response)
})
.catch(error =>{
console.log(error)
})
And then, i have this function which is called in that localhost route which attempts to get "licencia", and launch a select in my postgresql db where licencia="whatever", you can see the sentence in the code:
const getAtletasByLicencia = (request, response) => {
const licencia = request.body.licenciaInput;
console.log("Request: "+request);
console.log("what the server gets: "+licencia);
// const licencia = request.licenciaInput;
const sentencia ="SELECT * FROM atleta WHERE licencia ='"+licencia+"'";
pool.query(sentencia, (error, results) =>{
if(error){
throw error
}
response.status(200).json(results.rows)
})
}
As you can see, i have console.logs everywhere, and i still cannot access whatever element i send, because i always get on the server console "undefined" value.
TLDR:How can i access the "licenciaInput" i passed from my client form to my server, i have tried request.body.licenciaInput, request.params.licenciaInput, and request.licenciaInput, but none of those seem to work
I also know i have to treat after that the data i receive from the server, but i need to solve this before looking two steps ahead. Im also really new to React and node/express, so feel free to burn me with good practices im not meeting.Thanks in advance
EDIT: Im also adding this code that i have which shows the route for my method in the server:
app.get('/atletas/:licencia', db.getAtletasByLicencia)
As #Gillespie59 suggested that i should send a POST request, but i dont think i should if im both trying to send a parameter to the server to make a select, and then send the results back to the client
Change your request to:
axios.get(`http://localhost:3001/atletas/${this.state.licenciaInput}`)
...
and your route (if you are using express) should look like this:
app.get('/atletas/:licencia', function (req, res) {
var licencia = req.params.licencia
...
})
As you are using request.body you should send a POST request with axios and add a body.
I am trying to receive the raw response data, not the response headers or body. As an example, an image here shows the tab where this data is found:
Now, I am trying to receive this data when making an HTTP Request using `Axios`. Is this even possible?
I have tried searching online for about 2 hours, as this was a huge problem I was facing. I tried other sites, including stack overflow, to get the correct answer. If possible, could you please answer my question if you know? Thanks in advance.
const axios = require('axios');
const url = 'https://old.reddit.com/api/login?user=username&passwd=password'
function axiosTest() {
return axios.post(url).then((r) => {
console.log(r)
})
}
I'm pretty sure you must access the data property in the response object r. Also - since you are using the reddit API - make sure you are providing api_type in the request url (api_type=json for instance):
const axios = require('axios');
const url = 'https://old.reddit.com/api/login?api_type=json&user=username&passwd=password'
function axiosTest() {
return axios.post(url).then((r) => {
console.log(r.data)
return r.data;
})
}
For anyone reading this: Just to clarify, the api_type parameter in the request url is specific to the reddit API and most likely won't work any other API.
A friend has an API with a GET.
I would like to know if I can send data to a lambda with a get, as if I were using a simple POST.
I have this
await axios.post(
' ENDPOINT_API',
{
resultat_net_N1:`${resultat_net_N1_form}, ${resultat_net_N1}, ${resultat_net_N1_form_1}, ${resultat_net_N1_1}`,
resultat_net_N: `${resultat_net_N_form}, ${resultat_net_N}, ${resultat_net_N_form_1}, ${resultat_net_N_1}`,
},
);
I’d like a GET that behaves like this piece of code. I don't know if it's possible. Thanks in advance.
There are workarounds, but they aren't suggested, POST SHOULD BE TO POST, and GET SHOULD BE TO GET
const res = await axios.get("/ENDPOINT_API",
{ data: {
resultat_net_N1: resultat_net_N1 }
}
)
I suggest sending them as params
const res = await axios.get("/ENDPOINT_API",
{ params: {
resultat_net_N1: resultat_net_N1 }
}
)
It all depends on the use case you are sending the data. The Get method is exposing the data as query parameters and as the name suggest it is used for getting data from the API. POST method is not exposing the data like get and is used for sending data to the API in its request body. If you try to send sensitive data it is really not recommended to use get. You can find basic difference between the http methods and their usage here
I have to call 2 external api's, 2nd one is interdependent on the result of first one, i am not sure whether its better to call it Synch way or async way. I am also dumping the data to db, note that this function is called in the server and runs independent of client. This method runs at regular intervals. Below is my code. Can anybody please suggest me to do this in better way ?
getUser: function(){
console.log('getMultipleDeviceLocation');
this.unblock();
var arrayOfResponse = [];
try{
var userData = HTTP.call("GET", "url");
if(userData && !userData.error){
var userResult = userData.data;
var userDateTime = new Date();
for(key in result){
NetworkUsers.insert({
'dateTime': userDateTime,
'userid': userResult[key].userid,
'userName': userResult[key].userName
});
try{
var response = HTTP.call("GET","url"+result[key].userid);
if(response){
var result = response.data;
var dateTime = new Date();
DeviceView.insert({
'dateTime' : dateTime,
'nearAPs' : result.nearByAPs || '',
'userid' : result.userid,
'userName': result.userName
});
}
}catch(error){
console.log(error);
}
}
}else{
console.log('error');
}
}catch(error){
//Main Try Catch Block
console.log(error);
}
}
What i want here is once the first call is done and it returns a response i want those data to be dumped to the db and using the same data i want to make one more all call. Will async create problem here ? do i have to make it sync ?
Well, your actually doing sync HTTP call, which would usually work without any trouble.
I hope you just wrote "url" string to second param because you do not want to show what you're calling on ST. If not, you probably misunderstand something, you have to write the url adress of your api here.
var userData = HTTP.call("GET", "url");
#Julien Leray You mean to say, what i have written will work fine ?
You make me laught on this one; don't you test what your doing?
I dunno the API your trying to reach (like I said before, I hope you're just hidding it!). I don't know if it's work, but the concept should. You don't have anything crazy here, every call are sync, you shouldn't have any trouble.
Now, for going further, you could make it async. I propose you on commentary the Meteor.WrapAsync if you wanted to test pretty sweet Meteor features, but you could also make it vanilla, just by callback.
Eg Meteor.WrapAsync:
//dont want to show up my real Api Adress, using fake one
var url = "http://myApiUrl/foo/bar";
var options = {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}};
var getToSync = Meteor.wrapAsync(HTTP.get);
var data = getToSync(url, options);
//sweet, you can use data as if it was sync!
Do I well answered to your question or you're missing something?