How to use the fetch api method on Open Weather API - javascript

I'm trying to use the fetch method to display the current weather on a website. However, I keep getting an error stating that res is not defined. What do I need to do?
fetch('https://api.openweathermap.org/data').then(res => {
return res.json();
}).then(function(myJson) {
console.log(res.coord);
});
Note: The API call has been edited to ensure privacy

The problem is that you're using different parameter names in your functions. In your first function, you're using res:
.then(res => {
But in your second, you're using myJSON:
.then(function(myJson) {
Changing your code to this would fix your problem:
fetch('https://api.openweathermap.org/data').then(res => {
return res.json();
}).then(function(res) {
console.log(res.coord);
});

Related

timeoutSignal not working with node-fetch server side

I am trying to upgrade my node-fetch with the instructions here:
https://github.com/node-fetch/node-fetch/blob/HEAD/docs/v3-UPGRADE-GUIDE.md
I am able to get it to work and return a result when I don't set the signal option. I am not able to get the timeout working using timeoutSignal.
https://github.com/node-fetch/timeout-signal
const signal = timeoutSignal(5000); // This returns and empty AbortSignal object
// setting this causes an error, the fetch works without it
_.set(
opts,
'signal',
signal
);
const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));
fetchedResponse = await fetch(url, opts)
.then(response => {
console.log(response);
return response;
})
.catch(error => {
console.log(error);
})
If I change the property name 'signal' to anything else like 'signal-disable' or just remove it, everything works (without a timeout). The issue is that 'timeoutSignal(5000)' is returning an empty 'AbortSignal' object.
In the examples that I see, timeoutSignal seems to be always used in a client side scenario. I am not sure if this will work server side and can't find any examples.

Adyen Drop-in - how to pass unique order ID?

I have been trying to use the Adyen Drop-in component to make payments on the Razor pages site I am developing. I have got a test version running that makes a payment for a hard-coded amount but I have yet to figure out how to pass a unique order ID to my API endpoint making the payment request.
Taking the examples from https://docs.adyen.com/online-payments/drop-in-web, the drop-in component is mounted via JavaScript using
const checkout = new AdyenCheckout(configuration);
const dropin = checkout.create('dropin').mount('#dropin-container');
where the configuration object is created with something like
const configuration = {
paymentMethodsResponse: paymentMethodsResponse, // The `/paymentMethods` response from the server.
clientKey: "YOUR_CLIENT_KEY", // Web Drop-in versions before 3.10.1 use originKey instead of clientKey.
locale: "en-US",
environment: "test",
onSubmit: (state, dropin) => {
// Your function calling your server to make the `/payments` request
makePayment(state.data)
.then(response => {
if (response.action) {
// Drop-in handles the action object from the /payments response
dropin.handleAction(response.action);
} else {
// Your function to show the final result to the shopper
showFinalResult(response);
}
})
.catch(error => {
throw Error(error);
});
},
onAdditionalDetails: (state, dropin) => {
// Your function calling your server to make a `/payments/details` request
makeDetailsCall(state.data)
.then(response => {
if (response.action) {
// Drop-in handles the action object from the /payments response
dropin.handleAction(response.action);
} else {
// Your function to show the final result to the shopper
showFinalResult(response);
}
})
.catch(error => {
throw Error(error);
});
}
};
Adyen's own JavaScript then supplies the state object for the onSubmit method, so that my API endpoint gets called with a PaymentRequest object created (somehow) from the state.data.
However, without being able to get a unique order ID into this PaymentRequest object, my server-side code does not know what amount to set. Note that one can set an Amount object in the configuration object but this is just used to display the value on the Drop-in component - the value is not passed to the server.
So how does one pass a unique order ID via the Drop-in component?
The Adyen docs don't explicitly provide an example here, but the makePayment() and makeDetailsCall() presume that you will take the state.data and post back to your server. You need to implement your own code here. At that point, you could add additional information like any identifiers.
Here is an example implementation as a reference:
async function makePayment(state_data) {
const order_id = ""; // You need to provide this however your client stores it.
const json_data = {
order_id,
state_data,
};
const res = await fetch("[url to your server's endpoint]", {
method: "POST",
body: JSON.stringify(json_data),
headers: {
"Content-Type": "application/json",
},
});
return await res.json();
}
Another helpful resource could be the Adyen node.js/express tutorial. It is more explicit on implementation details so might help remove some ambiguity.

Data part of Response is a long script instead of desired json object

I am building a web app using laravel and vuejs. I have made a axios get request to get a list of users .
I am getting a Promise object, and from what i have read. Reason for getting a promise object is because it's an async request.
I have tried .then() to get data part of the response. But i am getting a huge script instead of desired data.
axios......then(function(response){
console.log(response.data);
})
Initially what i did was
var res = axios.get('/allUsers');
console.log(res)
That time i came to know about promise object and read about.
When i checked network in dev tools, status code is 200 and i can see list of users. So i guess my request is successfully completed.
What should be done to get the list of the users. That list i will be using to update my UI.
Depending on what you're getting back for data there are a few ways to handle this. You may need to convert the data after the you get receive the response.
axios.get('some_url')
.then(res => res.json())
.then(data => {
// do something with the data
}).catch(err) {
conosole.error(err);
}
if you're seeing the data come through properly in the response and you're getting what you need without doing that then just do
axios.get('some url').then(res => {
// do something in here with the data here
})
also make sure you're getting back json if that's what you're looking for. check your response to see if its html or json because they can be handled a bit differently
as an "Edit" you could also handle this with async await so you dont end up in callback hell
async function fetchData() {
try {
const res = await axios.get('some url');
// next step might not be necessary
const data = await res.json();
// do something with the data
console.log(data); // if converting it was necessary
console.log(res); // if not converting
} catch (err) {
console.error(err);
}
}

Vue: Best practices for handling multiple API calls

So I found myself making more than one API call in my vuex action and this let me to wonder what would be the best way to hanfle this situatons, the best practices for multiple API calls, let's begin with the code I have.
I have an action where I gather all posts and all post categories from different API endpoints (laravel for backend), I'm sure there's have to be a better way t hanfle this than how I'm doing it:
fetchAllPosts ({ commit }) {
commit( 'SET_LOAD_STATUS', 1);
axios.get('/posts')
.then((response) => {
commit('FETCH_ALL_POSTS', response.data.posts )
commit( 'SET_LOAD_STATUS', 2 );
},
(error) => {
console.log(error);
commit( 'SET_LOAD_STATUS', 3 );
})
axios.get('/postcategories')
.then((response) => {
commit('FETCH_ALL_POSTCATEGORIES', response.data.postcategories )
commit( 'SET_LOAD_STATUS', 2 );
},
(error) => {
console.log(error);
commit( 'SET_LOAD_STATUS', 3 );
})
},
First issue with my approach that I can think of is if the first API call fails but the second succeeds I will get a load status of 2 (2 equals success here) !
I only want to procced with the commits if BOTH the first and second API call correctly fetch the data, please help someone who is learning.
I think you may want to read about promises.
On your example you are using Axios, which is a Promise based HTTP Client and that's great.
With Promises you can do several requests, and when all requests are successful you can THEN execute code.
With Axios you can do that with .all like this:
axios.all([getPosts(), getPostCategories()])
.then(axios.spread(function (posts, categories) {
// Both requests are now complete
}));
axios.all([
axios.get(firstUrl),
axios.get(secondUrl)
])
.then(axios.spread(function (response1, response2) {
//response1 is the result of first call
//response2 is the result of second call
}))
.catch(function (error) {
});
Note about catch(): It is called on the first failing request omitting the rest of the calls. So if the first call fails, catch() is called without even making the second request.

Javascript File Download issue, returning strange string

I have the following HTTP Axios getcall that should result the browser to force a download but I get the a strange result instead.
AXIOS Call
axios.get('http://localhost:63464/api/Consumer/ExcelDownload')
.then(res => {
return res.data;
})
.then(res =>
{
console.log(res);
})
.catch(err =>
{
console.log(err)
})
Which is returning the following result from the line in console.log(res);
Result of console.log(res.data) image Here
I was doing the following in the past to get this to work.
location.href = 'http://localhost:63464/api/Consumer/ExcelDownload';
which would return my File result.
however this route is now protected using a JWT which I have set in axios global headers, so this is no longer working for me.
Would someone be able to help me with this issue?
perhaps even being able to create some kind of URL from a blob that I can make the same call to.

Categories

Resources