I have the following in my typescript file
async createProduct(data) {
return await axios.post(request).catch(error => {
console.log('error'.bgRed.white.bold, error)
});
}
that error looks like this when logged
I need to single out the error from the outside api which looks like this
How do I single out that part like any other object ie return error.title
Update
here is the full response https://jsoneditoronline.org/#left=cloud.c584e42736664e9595fcfd8bb9c668a4
Try const errorObject = JSON.parse(error.config.data).
If the syntax in the string is correct, you should be able to access the title as usual errorObject.title
Related
I have a question I've spent the past few days with my friend google trying to answer. This is the code from a project I'm currently working on and I'm trying to interface with two API's.
What you see here is a call to the first API using the GOT library formatting to receive a JSON response.
var products
//Printify call for products list
(async () => {
try{
const list = await redd('shops/shopId/products.json');
//Catch the Data array and save it into the variable products
var obj = new JSONObject(response);
products = obj.getJSONArray("data");
}
catch(error) {
}
})();
//Print the variable products to the console
console.log(products)
I create a new JSONObject from the response and grab the Data Array from that response and put it in the Variable products which was defined outside this function. Finally I'm trying to print the variable to the console.
Eventually I will need to take that "data" Array and parse for specific items inside it (i.e. title: , description: , images:) and pass it as a value into the next API.
Currently I'm getting a "undefined" response from the console. Not sure what I'm doing wrong, hoping that I can get some help or direction. Anything is appreciated, thank you all in advance!
I was finally able to get it all working. It's actually been a minute since I solved, but wanted to make sure it worked. Here is the final code that ended up working for me:
//Config for a new GOT instance, to use redd as the variable with the attached headers and options
const redd = got.extend({
prefixUrl: 'https://api.printify.com/v1',
responseType: 'json',
headers: {
'Authorization': 'Bearer ' + apiKey
}
});
var productsParsed //Setting up global variable to accept the array from the JSON response body
//Printify call for products list
getProducts = async () => {
try{
const response = await redd('shops/' + shopId + '/products.json');
productsParsed = response.body.data; //Data is the array in the body I need access to, and saving that into the var productsParsed
//Returning the var with the new value
return productsParsed
}
catch(error) {
console.log(error.response);
}
};
getProducts().then(console.log); //Printing the return value from getProducts() which verifies the var contains the needed value
So the solution ended up being fairly simple. I just didn't fully understand the GOT structure. I had to use dot notation to pin down my return statement. After figuring that out I was able to use my global variable that I had set up to accept the value of the JSON response body. Thank you all for your suggestions and assistance. I hope this post is able to help any others in a similar situation to myself.
You've defined an async function, but you haven't awaited its result.
I think adding await in front of the call site would fix that.
Because it's an async function the console.log is called before the async function is finished. Move it inside the async function and it should work.
var products
//Printify call for products list
(async () => {
try{
const list = await redd('shops/shopId/products.json'); // we wait for the response here
//Catch the Data array and save it into the variable products
var obj = new JSONObject(response);
products = obj.getJSONArray("data");
//Print the variable products to the console will work here
console.log(products)
}
catch(error) {
}
})();
I looked a bit on the web and couldn't find a good answer to my question, so I'll ask it to you guys.
I have an async function, that gets true/false data from an API, I am able to print the value that I got from the API, but when I return that value, I get an "Undefined" instead.
I feel like the problem is in the way that I return that variable, but like I said I haven't been able to find an answer, so if someone know how to that would be wonderful.
Here is the function:
const CheckSource = async function(AttId, symbolId){
//creates the get parameters
var SourceGetParams = Helper.returnGetOptions(`SignalValues/${symbolId}/${AttId}`);
//send the get request and waits for responce
await Helper.sendRequest(SourceGetParams).then((res, body) => {
//parses the response, prints the correct value, but returns "undefined"
var response_body = JSON.parse(res.body);
var value = response_body.API_Signals[0].RawValue
console.log(value);
return Promise.resolve(value);
//error handling
}, (error) => {
console.log('error sending source get request:', error);
return Promise.reject('There was an error with the fusion request.');
}).catch((error) => {
console.log('Source sendRequest promise error:', error);
return Promise.reject('There was an internal error sending the request.');
}); }
I have tried to use different methods to return the value (such as 'return value;') but I get the same result.
Here is how I call the function:
CheckSource(<Att_ID string here>, <Symbol_ID string here>).then((data)=>{
console.log(data)
});
I know this is a question that is often asked, and I tried many of the other answers found here, but got no results.
The answer I get is this:
False //(this is the expected output from the conslole.log() in the async function)
undefined //(this is the console.log() after I called the function)
I really appreciate all of you.
What I can see in your code is, the function check source is returning a resolved promise from inside of another function and when you are calling it, you are trying to resolve the promise using then and catch. That should not be the case. Try a console log like this
console.log(CheckSource());
This should print False.
I'm getting this error "TypeError: Cannot read property '0' of undefined" when I want to extract a data from JSON file.
However, the data I want to extract is not available every time I request a JSON file, therefore, I'm getting this error which makes my Node.js Application to crash every time I'm getting this error.
simply check if it exists or not:
if (json && json['Name'] && json['Name']['Nationality']) {
data = json['Name']['Nationality'][0];
} else {
// no data, do whatever error handling you want here
}
A solution for this sort of problem is using try-catch:
try {
data = json['Name']['Nationality'][0];
} catch (error) {
data = "Sorry no data found"
}
The try function is going to run the code if it did find any error it will pass it to catch.
In my React/Redux app, I make a call to my backend API which returns a text response. I then use the following line to retrieve the text. The issue I'm seeing is that my code seems to put two sets of quotes around the text I receive.
So, my API returns Hello World! but in the code below it becomes ""Hello World!""
My API is really returning a string so there will always be a set of quotes around the text such as "Hello World!" which is perfectly fine. I just don't understand why I'm getting two sets of quotes.
Any idea why?
export const callApi = (request) => {
return (dispatch) => fetch('/api/getsometext', fetchOptionsPost(request))
.then((response) => {
if(!response.ok) {
// Request failed
dispatch(setBadRequest(true))
} else {
const myText = response.text() // This is where I'm getting double quotes
.then((myText) => dispatch(setMyText(myText)))
}
})
}
Simply quoting #Kaiido's hint as an answer so I does not get lost in the comments:
Your server sends the data with these quotes, probably because it
thinks it should send it as JSON. So either reconfigure your API so it
doesn't try to send it as JSON, either simply use Response.JSON() so
that your client-side parses it correctly.
I seem to be misunderstanding how flowtype refinements work (or maybe my Nuclide/Atom + Flow setup is being dumb). I'd like to do something like the following:
async function getIp(): Promise<string> {
const resp = await fetch('https://httpbin.org/ip')
const json = await resp.json() // `json: any` at this point
if (typeof json.ip === 'string') {
return json.ip
} else {
throw new Error("Weird response.")
}
}
I'm fetching some JSON from an API endpoint, and it has type any. I'd like to sanity check that it has the right form (e.g. that it has a string ip field). Nuclide however warns me that every use of json in the above code is "Not covered by flow", including the entire json.ip expression. Why is that? I would have expected the typeof check to refine the type of json.ip to string.
Is there another way to refine untyped values?
Edit: Here's a tryflow example of what I'm seeing.
No, you can't refine any. You already can do anything with it, so what's the point?
If you want Flow to verify your code you should immediately convert your any to mixed:
const json: mixed = await resp.json()