I want to retrieve the JSON response from the api call I am doing. Example, I want to retrieve something like this:
{"error":{},"success":true,"data":{"user":"tom","password":"123","skill":"beginner","year":2019,"month":"Mar","day":31,"playmorning":0,"playafternoon":1,"playevening":1}}
This is my API call using fetch in react. (yes I know sending password in URL is bad, it's for a school project)
fetch('/api/user/'+ user + '?password=' + password, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}}).then((res) => {
console.log(res); //I want to get the JSON stuff here
})
This is the API call I am calling.
app.get('/api/user/:user', function (req, res) {
// console.log(JSON.stringify(req));
// var user = req.body.user;
// var password = req.body.password;
var user = req.params.user;
var password = req.query.password;
console.log(user, password);
var result = { error: {} , success:false};
if(user==""){
result["error"]["user"]="user not supplied";
}
if(password==""){
result["error"]["password"]="password not supplied";
}
if(isEmptyObject(result["error"])){
let sql = 'SELECT * FROM user WHERE user=? and password=?;';
db.get(sql, [user, password], function (err, row){
if (err) {
res.status(500);
result["error"]["db"] = err.message;
} else if (row) {
res.status(200);
result.data = row;
result.success = true;
} else {
res.status(401);
result.success = false;
result["error"]["login"] = "login failed";
}
res.json(result);
});
} else {
res.status(400);
res.json(result);
}
});
When I do console.log(res) in the fetch call, this is what is printed:
Response {type: "basic", url: "http://localhost:3000/api/user/tim?password=123", redirected: false, status: 200, ok: true, …}body: (...)bodyUsed: falseheaders: Headers {}ok: trueredirected: falsestatus: 200statusText: "OK"type: "basic"url: "http://localhost:3000/api/user/tim?password=123"proto: Response
When I visit the website, the output is:
{"error":{},"success":true,"data":{"user":"tom","password":"123","skill":"beginner","year":2019,"month":"Mar","day":31,"playmorning":0,"playafternoon":1,"playevening":1}}
This is what I want.
In general, this is how you return the response body from the Promise.
fetch(`${baseUrl}/api/user/${user}?password=${password}`, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}})
.then(response => response.json())
.then(data=> {
console.log(data);
})
Try this way to parse the response:
fetch('/api/user/'+ user + '?password=' + password, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}}).then(async (res) => {
const raw = await res.text();
const parsed = raw ? JSON.parse(raw) : { success: res.ok };
console.log(parsed);
})
In this case you can also add some checks for response statuses (if you want, of course) along with parsing the result JSON.
for you to get the JSON body content from the response, you need to use json()
fetch('/api/user/'+ user + '?password=' + password, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}}).then((res) => {
const jsonData = res.json();
console.log(jsonData);
})
try this
fetch(${baseUrl}/api/user/${user}?password=${password},{
method:'GET',
headers: {
'Accept': 'application/json',
'Content-Type':
'application/json',
}}) .then(async(response ) => {
await response.json()
})
Related
I want to use received data from server on client . I use a NodeJS Server with NextJS and React.
I use this function on the server:
function addEmailToMailChimp(email, callback) {
var options = {
method: 'POST',
url: 'https://XXX.api.mailchimp.com/3.0/lists/XXX/members',
headers:
{
'Postman-Token': 'XXX',
'Cache-Control': 'no-cache',
Authorization: 'Basic XXX',
'Content-Type': 'application/json'
},
body: { email_address: email, status: 'subscribed' },
json: true
};
request(options, callback);
}
The function will be run from this point:
server.post('/', (req, res) => {
addEmailToMailChimp(req.body.email, (error, response, body) => {
// This is the callback function which is passed to `addEmailToMailChimp`
try {
var respObj = {}; //Initial response object
if (response.statusCode === 200) {
respObj = { success: `Subscribed using ${req.body.email}!`, message: JSON.parse(response.body) };
} else {
respObj = { error: `Error trying to subscribe ${req.body.email}. Please try again.`, message: JSON.parse(response.body) };
}
res.send(respObj);
} catch (err) {
var respErrorObj = { error: 'There was an error with your request', message: err.message };
res.send(respErrorObj);
}
});
})
The try method is used to verify that an email address could be successfully saved to MailChimp. An appropriate message is sent to the client.
On the Client-Side, i use this function to receive and display the data from the server:
handleSubmit() {
const email = this.state.email;
this.setState({email: ""});
fetch('/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({email:email}),
}).then(res => {
if(res.data.success) {
//If the response from MailChimp is good...
toaster.success('Subscribed!', res.data.success);
this.setState({ email: '' });
} else {
//Handle the bad MailChimp response...
toaster.warning('Unable to subscribe!', res.data.error);
}
}).catch(error => {
//This catch block returns an error if Node API returns an error
toaster.danger('Error. Please try again later.', error.message);
});
}
The problem: The email address is saved successfully at MailChimp, but the message is always displayed: 'Error. Please try again later.'from the .catch area. When i log the error from the catch area i get this:
TypeError: Cannot read property 'success' of undefined
Where is my mistake? I have little experience in Node.js environments. I would be very grateful if you could show me concrete solutions. Thank you for your replies.
With fetch theres no data property on the response. You have to call res.json() and return that promise. From there the response body will be read and deserialized.
handleSubmit() {
const email = this.state.email;
this.setState({email: ""});
fetch('/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({email:email}),
})
.then(res => {
console.log(res); //to make sure the expected object is returned
if(res.data.success) {
//If the response from MailChimp is good...
toaster.success('Subscribed!', res.data.success);
this.setState({ email: '' });
} else {
//Handle the bad MailChimp response...
toaster.warning('Unable to subscribe!', res.data.error);
}
}).catch(error => {
//This catch block returns an error if Node API returns an error
toaster.danger('Error. Please try again later.', error.message);
});
}
Two things you need to change:
Call and wait for res.json() to get the response body as json object.
The result of 1. is your 'data' object that you can use directly
handleSubmit() {
//...
fetch('/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({email:email}),
})
.then(res => res.json())
.then(data => {
if(data.success) {
//...
toaster.success('Subscribed!', data.success);
} else {
toaster.warning('Unable to subscribe!', data.error);
}
}).catch(error => {
//...
});
}
This is my function in NodeJs app which I am using to create user in openfire.
var createUser = function(objToSave, callback) {
const options = {
method: 'POST',
uri: url.resolve(Config.APP_CONSTANTS.CHAT_SERVER.DOMAIN_NAME, '/plugins/restapi/v1/users'),
headers: {
'User-Agent': 'Request-Promise',
'Authorization': Config.APP_CONSTANTS.CHAT_SERVER.SECRET_KEY,
'Accept': 'application/json',
'Content-Type': 'application/json',
},
data: objToSave
}
request(options)
.then(function(response) {
callback(null, response);
})
.catch(function(error) {
// Deal with the error
console.log(error);
callback(error);
});
};
the objToSave is a json object contains username and password.
{
"Username": "gabbar",
"Password": "gabbar#123"
}
when i run this function i am getting the following error..
{
"statusCode": 400,
"error": "Bad Request"
}
I configured my secret-key properly and domain name is localhost://9090, can anybody tell me what I am doing wrong ? thanks in advance.
I think the options you provided needs JSON.stringify object before send it
The modified options is as below
const options = {
method: 'POST',
uri: url.resolve(Config.APP_CONSTANTS.CHAT_SERVER.DOMAIN_NAME, '/plugins/restapi/v1/users'),
headers: {
'User-Agent': 'Request-Promise',
'Authorization': Config.APP_CONSTANTS.CHAT_SERVER.SECRET_KEY,
'Accept': 'application/json',
'Content-Type': 'application/json',
},
data: JSON.stringify(objToSave)
}
I find out that problem was with request-promise. it was not properly sending data in the required format. so Instead of that now I am using different module minimal-request-promise. and It worked like charm for me. After using that, my code looks something like this.
var requestPromise = require('minimal-request-promise');
var createUser = function(objToSave, callback) {
const options = {
headers: {
'Authorization': Config.APP_CONSTANTS.CHAT_SERVER.SECRET_KEY,
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(objToSave)
};
requestPromise.post('http://localhost:9090/plugins/restapi/v1/users', options)
.then(function(response) {
callback(null, response);
})
.catch(function(error) {
// Deal with the error
console.log(options);
console.log(error);
callback(error);
});
};
I am retrieving a password asynchronously and this is working fine:
static async login(){
let password = await User.getPassword();
alert(password); // this works, password is shown
But if I want to use it inside fetch it dose not work
static async login(){
let password = await User.getPassword();
alert(password); // this works, password is shown
return fetch(userInfoURL,
{ method: 'GET',
headers: { 'Authorization': password,
'Content-Type': 'application/json'}
})
the password received by the server is empty
I also tried
User.getPassword().then((password) => {
return fetch(userInfoURL,
{ method: 'GET',
headers: { 'Authorization': password,
'Content-Type': 'application/json'}
})
but I had the same problem, password is empty.
You have to await the fetch
return await fetch(userInfoURL,
{ method: 'GET',
headers: { 'Authorization': password,
'Content-Type': 'application/json'}
})
async getTabList(userId){
try{
let params = 'userId='+userId;
let myR = await myRequest([yourURL],params);
let response = await fetch(myR);
let responseJson = await response.json();
if(responseJson.code === 0){
return responseJson;
}else{
Toast.fail('失败');
return {};
}
} catch (error){
Toast.fail('异常,请联系管理员');
}
}
function myRequest(url,params){
return new Request(url,{
method:'POST',
headers:{
'Content-Type': 'application/x-www-form-urlencoded',
// 加密
},
body:params,
});
}
I have a oauth set up. But when I want to get the access token with the fetch() function it just returns an object with things like _bodyInit, _bodyBlob and headers. So I just cannot get a JSON object. I'm on Android if that matters in any way.
Code:
componentDidMount() {
Linking.getInitialURL().then(url => {
if(url) {
console.log(url);
const queries = url.substring(16)
const dataurl = qs.parse(queries);
if(dataurl.state === 'ungessable15156145640!') {
console.log(dataurl.code);
console.log(dataurl.state);
return code = dataurl.code;
}
}
}).then((code) => {
fetch(`https://dribbble.com/oauth/token`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
'client_id': 'MY_ID',
'client_secret': 'MY_SECRET',
'code': code
})
})
.then((res) => {
var access_token = res;
console.log(access_token);
});
});
}
You almost got it right, you are missing one step though!
fetch doesn't return a json object, it returns a Response object, in order to get the json object, you have to use res.json()
fetch(`https://dribbble.com/oauth/token`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
'client_id': 'MY_ID',
'client_secret': 'MY_SECRET',
'code': code
})
})
.then((res) => {
return res.json();
})
.then((json) => {
console.log(json); // The json object is here
});
It's a good practice to add a catch just in case something goes wrong.
.then((json) => {
console.log(json); // The json object is here
});
.catch((err) => {
// Handle your error here.
})
I have a oauth set up. But when I want to get the access token with the fetch() function it just returns an object with things like _bodyInit, _bodyBlob and headers. So I just cannot get a JSON object. I'm on Android if that matters in any way.
Code:
componentDidMount() {
Linking.getInitialURL().then(url => {
if(url) {
console.log(url);
const queries = url.substring(16)
const dataurl = qs.parse(queries);
if(dataurl.state === 'ungessable15156145640!') {
console.log(dataurl.code);
console.log(dataurl.state);
return code = dataurl.code;
}
}
}).then((code) => {
fetch(`https://dribbble.com/oauth/token`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
'client_id': 'MY_ID',
'client_secret': 'MY_SECRET',
'code': code
})
})
.then((res) => {
var access_token = res;
console.log(access_token);
});
});
}
You almost got it right, you are missing one step though!
fetch doesn't return a json object, it returns a Response object, in order to get the json object, you have to use res.json()
fetch(`https://dribbble.com/oauth/token`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
'client_id': 'MY_ID',
'client_secret': 'MY_SECRET',
'code': code
})
})
.then((res) => {
return res.json();
})
.then((json) => {
console.log(json); // The json object is here
});
It's a good practice to add a catch just in case something goes wrong.
.then((json) => {
console.log(json); // The json object is here
});
.catch((err) => {
// Handle your error here.
})