Getting values from response - javascript

I am getting the response from an external api like the given below screenshot.
How can i get the value of id i.e., 3991938
Here is how i do the request.
$http.post('http://api.quickblox.com/users.json', {
token: quickbloxapitoken,
user: {
email: email,
login: email,
password: password
}
}, {
'Content-Type': 'application/x-www-form-urlencoded'
})
.then(function(results) {
console.log('1');
console.log(results);
console.log('2');
})
.catch(function(response) {
console.log('Error', response.status, response.data.errors);
});
I tried to do console.log(results.id); and console.log(results.data.id) but i am getting only undefined as the result.
How can i get it.

Your JSON is:
{
data: {
user: {
id: 65
}
}
}
You can acces to user data with results.data.user, eg: results.data.user.id

you id is in user object,
so what you need is :-
results.data.user.id

Related

No data in GET response

Trying to make a GET Request to SAP OData. The connections works -> response status is 200 but console.log(res) doesnt give me any json objects, i just get some information about the request, response url and so on.
axios.get(url,{
withCredentials: true,
params: {
json:true
},
auth: {
username: 'blablablablabla',
password: 'blub123blub123blub123'
}
})
.then(res => {
console.log(res.status);
console.log("success!");
console.log(res);
})
.catch(err => {
console.log(err.message);
console.log(err.response.status);
})
The solution was
console.log(JSON.stringify(res.data));
thanks to ziga1337 for the hint

React with Node getting json data from res.status.json()

I am running a react app with nodejs acting as an api to connect to my database.
For my log in I am sending data to the server, and it is returning a pass or fail.
However I am not sure how to extract this json object.
I have looked at the request and response, and as I have manipulated the json object the response content-length has been changing so I believe it must be there somewhere.
SERVER CODE:
app.post('/api/checkLogin', async (req,res) => {
console.log(req.body);
const {username, password} = req.body;
try{
let state = await DB.checkPassword(username, password);
console.log(state);
if(!state){
res.status(401).json({
error: 'Incorrect username or password',
yay: 'idk work?'
});
}
else if(state){
res.status(200).json({
message: 'we in boys'
});
} else {
res.status(6969).json({
err: 'idk mane'
});
}
} catch(e) {
console.log(e);
}
})
CLIENT CODE:
onSubmit = (event) => {
event.preventDefault();
fetch('/api/checkLogin', {
method:'POST',
body: JSON.stringify({username: this.state.username, password: md5(this.state.password)}),
headers: {
'Content-Type':'application/json'
}
}).then(res => {
if(res.status ===200) {
this.props.loggedIn();
} else if(res.status ===401){
console.log(res.status);
alert('wrong username or password');
}else{
const error = new Error(res.error);
throw error;
}
}).catch(err => {
console.log(err);
alert(err);
});
}
What I was sort of expecting as a way to extract the data would be.
On the server:
res.status(200).json({ message : 'mssg'});
On the client:
console.log(res.status.message) // 'mssg'
Thanks Jin and this post I found for the help Fetch API get raw value from Response
I have found that both
res.status(xxx).json({ msg: 'mssg'}) and res.status(xxx).send({msg: 'mssg'}) work.
The json, or sent message can then be interpreted on the client side with a nested promise. This is done with...
fetch('xxx',headers n stuff).then(res => {
res.json().then((data) => {console.log(data.message)});
//'mssg'
res.text().then((data) => { let data1 = JSON.parse(data); console.log(data1.message);});
//'mssg'
});
According to my experience, using res.status(200).send({message: 'mssg'}) is better.
And you can get data after calling api by using res.data.
Then you can get result as below:
{
message: 'mssg'
}
Here is something that may help.
onSubmit = (event) => {
event.preventDefault();
const userData = {
username: this.state.username, // I like to store in object before passing in
password: md5(this.state.password)
}
fetch('/api/checkLogin', {
method:'POST',
body: JSON.stringify(userData), //stringify object
headers: {
'Content-Type':'application/json'
}
}).then(res => res.json()) // convert response
.then(responseData => {
let status = responseData.whatObjectWasPassedFromBackEnd;
status === 200 ? do something on pass: do something on fail
})
.catch(err => {
console.log(err);
alert(err);
});
}

How to post query parameters with Axios?

I am trying to post on an API with some query params.
This is working on PostMan / Insomnia when I am trying to by passing mail and firstname as query parameters :
http://localhost:8000/api/mails/users/sendVerificationMail?mail=lol%40lol.com&firstname=myFirstName
However, when I am trying to do it with my react native app, I got a 400 error (Invalid Query Parameters).
This is the post method :
.post(`/mails/users/sendVerificationMail`, {
mail,
firstname
})
.then(response => response.status)
.catch(err => console.warn(err));
(my mail and firstname are console.logged as follow: lol#lol.com and myFirstName).
So I don't know how to pass Query Parameters with Axios in my request (because right now, it's passing data: { mail: "lol#lol.com", firstname: "myFirstName" }.
axios signature for post is axios.post(url[, data[, config]]). So you want to send params object within the third argument:
.post(`/mails/users/sendVerificationMail`, null, { params: {
mail,
firstname
}})
.then(response => response.status)
.catch(err => console.warn(err));
This will POST an empty body with the two query params:
POST
http://localhost:8000/api/mails/users/sendVerificationMail?mail=lol%40lol.com&firstname=myFirstName
As of 2021 insted of null i had to add {} in order to make it work!
axios.post(
url,
{},
{
params: {
key,
checksum
}
}
)
.then(response => {
return success(response);
})
.catch(error => {
return fail(error);
});
In my case, the API responded with a CORS error. I instead formatted the query parameters into query string. It successfully posted data and also avoided the CORS issue.
var data = {};
const params = new URLSearchParams({
contact: this.ContactPerson,
phoneNumber: this.PhoneNumber,
email: this.Email
}).toString();
const url =
"https://test.com/api/UpdateProfile?" +
params;
axios
.post(url, data, {
headers: {
aaid: this.ID,
token: this.Token
}
})
.then(res => {
this.Info = JSON.parse(res.data);
})
.catch(err => {
console.log(err);
});
You can use params and body together in a request with axios
sendAllData (data) {
return axios
.post(API_URL + "receiveData", JSON.stringify(data), {
headers: { "Content-Type": "application/json; charset=UTF-8" },
params: { mail: xyx#example.col }, //Add mail as a param
})
.then((response) => console.log("repsonse", response.status));
}

React Js Axios Post Request not receiving body back from web api

So I have a web api that is set up to generate a token for to return when you send it a username and password that are the same this works through postman if you give a body like so
this works it gives you a token and the correct information but when i do it from chrome, firefox or ie it gives me an error my code is this,
var d = {
username: Uname,
surname: Pword,
grant_type: "password",
client_id: "099153c2625149bc8ecb3e85e03f0022",
};
console.log(d);
var self = this;
return (
axios.post('http://localhost/hydraauth/oauth/token', {
headers: {
'Content-Type': 'application/json',
},
data: d
}).then(function (response) {
console.log(response.data)
self.setState({
isLoggedIn: true,
Uname: Uname,
}, function () {
sessionStorage.setItem("Login", true);
sessionStorage.setItem("Uname", Uname)
window.location.href = "/";
});
}).catch(function (error) {
if (error.response){
console.log(error.response)
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else {
window.alert("Incorrect Username Or Password Or Unauthorized To Access This.")
}
})
);
which gives me this error in chrome
here is the error expanded
image of the network tab in chrome the response tab is empty
Axios has an issue with sending data via body so you need to use npm plugin query string
and use it like so
axios.post("http://localhost/hydraauth/oauth/token", querystring.stringify({ "username": Uname, "password": Pword, "grant_type": "password", "client_id": "eyJjbGllbnRfaWQiOiJTYXZ2eS1Dcm0tUmVhY3QtSnMtU3lzdGVtIn0" }))

MeteorJS call rest api server side

Now i call rest API with:
Template.accedi.events({
'submit #form-login'(e) {
e.preventDefault();
var data = {
'username': $("[name=login_username]").val(),
'password': $("[name=login_password]").val()
};
var url = api_url + "/Token";
HTTP.call('POST', url, {
params: {
'grant_type': 'password',
'username': data.username,
'password': data.password
}
}, (error, result) => {
if (!error) {
Session.set('userData', JSON.stringify(result.data));
localStorage.setItem('userData', JSON.stringify(result.data))
Router.go('/');
}
}
}
})
This call rest api client side.
I need to call the api server side... there is a method?
You should create method which is then called from your client code. Something like below should works in your case.
Methods have to be defined in code which is loaded on the client and server.
Meteor.methods({
'login.token'({ username, password }) {
try {
let request = HTTP.call('POST', 'https://example.com', {
params: {
'grant_type': 'password',
'username': username,
'password': password
}
})
// You might want to process, validate etc. request response before return it to the client.
return request
} catch (err) {
throw new Meteor.Error(500, 'There was an error processing your request')
}
}
})
Your client code might looks similiar to this
Template.accedi.events({
'submit #form-login'(e) {
e.preventDefault();
var data = {
'username': $("[name=login_username]").val(),
'password': $("[name=login_password]").val()
};
Meteor.call('login.token', {
username: data.username,
password: data.password
}, (err, res) => {
if (err) {
console.log(err)
} else {
Session.set('userData', JSON.stringify(res.data));
localStorage.setItem('userData', JSON.stringify(res.data))
Router.go('/');
}
})
}
})
You can find more about methods in Meteor guide at this page https://guide.meteor.com/methods.html

Categories