*New to express.
I have index.ejs and script.js.
My script fetches some JSON data from an api just fine.
const fetch = require("node-fetch");
const url = '...'
fetch (url)
.then(response => {
return response.json()
})
.then(data =>{
console.log(data)
})
.catch(err => {
})
How would I go about using this returned JSON data to create a chart in my index page with d3.
I have searched around but am still confused. Any advice would be super helpful! Thanks.
So as discussed in the comments, the problem was having a server which is return in express framework of nodejs
So in express code need to call an api and get data, once we get the data we need to send it to the front end.
So for returning data to front end we can use res.send of express
const fetch = require("node-fetch");
const url = '...'
fetch (url)
.then(response => {
return response.json()
})
.then(data =>{
console.log(data)
res.send(data)
})
.catch(err => {
})
And in the front end we need to access this api as shown below
const getData = async () => {
try {
const response = await fetch(url) // server url (express js route) example http://localhost:6000/api/getChartData
if(response.ok){
const body = await response.json()
console.log(body)
// once you get the data you can create d3 chart
return
}
const customError = {
message: 'something went wrong'
}
throw customError
}catch(error){
console.log(error)
// put the error in a variable and display on the ui so the user know some error happened
}
}
Related
my fetch is stuck in pending when I query a fastapi endpoint in local dev.
followed this blog and a few others - https://damaris-goebel.medium.com/promise-pending-60482132574d
Using this fetch code (having simplified it drastically just to get a simple solution working)
function fastapiRequest(path) {
return fetch(`${path}`)
.then((response) => {
return response;
}
);
into a constant variable i.e.,
const xxxx = fastapiRequest(
`http://0.0.0.0:8008/xcascasc/Dexaa/Emo.json?Magic=Dexxaa&emotion=expressions`
);
Ideally I want to use UseSWR to do this as I'm using next.js, but first of all, just need it to work :)
A postman query like this works fine to return a value
curl --location --request GET 'http://0.0.0.0:8008/xcaxc/dexxa/emo.json?analysis=statistical&substance=dexxa&emo=powa' \
--header 'x_token: 13wdxaxacxasdc1'
the value is left like this in console.log
data show here? Promise {<pending>}
With the initial response being
Response {type: 'cors', url: 'url', redirected: false, status: 200, ok: true, …}
Update based on answers.
Using each of the proposed answers, I am still not getting the data returned appropriately. i.e.,
function fastApiRequest(path) {
console.log("really begins here");
return fetch(`${path}`, { mode: 'cors' })
.then((response) => {
console.log('response', response);
return response.json();
})
.catch((err) => {
throw err;
});
}
async function test() {
console.log('begins');
return await fastApiRequest(
`http://0.0.0.0:8008/xxxx/dex/adea.json?deaed=adedea&adee=deaed&adeada=adeeda`
);
}
const ansa = test();
Is giving a response of pending at the moment.
The backend is built with fastapi, with these CORS, I'm wondering if I need to give it more time to get the data? (postman works fine :/)
def get_db():
try:
db = SessionLocal()
yield db
finally:
db.close()
origins = [
"http://moodmap.app",
"http://localhost:3000/dashboard/MoodMap",
"http://localhost:3000",
"http://localhost",
"http://localhost:8080",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
max_age=3600,
)
I am running the fastapi code in a docker container as well btw
As per Documentation
The Response object, in turn, does not directly contain the actual JSON response body but is instead a representation of the entire HTTP response. So, to extract the JSON body content from the Response object, we use the json() method, which returns a second promise that resolves with the result of parsing the response body text as JSON.
.json() is an async method (it returns a Promise itself), so you have to assign the parsed value in the next .then(). So your code can be changed like this.
function fastApiRequest(path) {
let res;
fetch(`${path}`)
.then((response) => response.json())
.then((data) => (res = data))
.then(() => console.log(res));
return res;
}
response = fastApiRequest('https://proton.api.atomicassets.io/atomicassets/v1/accounts?limit=10');
console.log('response')
If you want to use async/await approach, below is the code.
async function fastApiRequest(path) {
try {
const response = await fetch(path);
const data = await response.json();
return data;
} catch (error) {
console.error(error);
}
}
async function test() {
console.log(await fastApiRequest('https://proton.api.atomicassets.io/atomicassets/v1/accounts?limit=10'))
}
test()
first you need to parse the response into json if it's a json API.
function fastapiRequest(path) {
return fetch(`${path}`)
.then((response) => {
return response.json();
});
}
you need to 'await' for the rsponse
you need to write the below code in an async function
const xxxx = await fastapiRequest(
`http://0.0.0.0:8008/xcascasc/Dexaa/Emo.json?Magic=Dexxaa&emotion=expressions`
);
When you make an http request using fetch in javascript it will return a Promise, it's not stuck it's just need to be resloved, you can resolve it just like the above code with async await, or you can use the .then(() => { /* code... */ }) function, you can also use .catch(() => { /* handle error... */ }) function to handle errors.
In Your curl you use x_token as header variable, if it's required you need to pass a header with your path too. All other answers are valid too.
I am new to the Hapi.js node extension.
I am trying to call an external API into my server because the external API is protected with CORS and I can't call it from my front (Angular 9).
So I set up my hapi server with routes etc and now in a route I am trying to import the external data and when the front call the route of my hapi api it show the data from the external API.
I didn't find any documentation or already topics about this problem, if you could provide me with some information it would be very helpful!
(I want to do my external API call from the route solcast)
This is my index.js :
'use strict';
require('dotenv').config()
const Hapi = require('#hapi/hapi');
const init = async () => {
const server = Hapi.server({
port: 3000,
host: 'localhost',
routes: {
cors: true
}
});
server.route(require('./routes/base').test);
server.route(require('./routes/solcast').solcast);
await server.start();
console.log('Server running on %s', server.info.uri);
};
process.on('unhandledRejection', (err) => {
console.log(err);
process.exit(1);
});
init();
This is my solcast.js :
This while console.log the error :
Error: handler method did not return a value, a promise, or throw an error
And then console.log the data. I assume that the data is not received when the return is done.
const joi = require('#hapi/joi');
const fetch = require("node-fetch");
exports.solcast = {
method: 'GET',
path: '/solcasttest',
handler: (request, h) => {
fetch("https://linkToTheExternalApi")
.then(response => response.json())
.then(data => {
console.log(data)
return data
})
.catch(err => console.log(err))
console.log(testSolcast)
}
}
Thank you for your help, if you need any other information hit me up.
As the error thrown suggests, a handler in hapi.js must return a value, a promise or throw an error.
In your case, the handler is an asynchronous operation, so you have to return a promise.
As fetch already creates a promise, it is enough if you return the promise created by fetch in your handler :
const fetch = require("node-fetch");
exports.solcast = {
method: 'GET',
path: '/solcasttest',
handler: (request, h) => {
return fetch("https://linkToTheExternalApi")
.then(response => response.json())
.then(data => {
console.log(data)
return data
})
.catch(err => console.log(err));
}
}
I was doing a pretty easy task of getting information from an API but then i got the response as ReadableStream and things start to turn dark as always. I am trying to use the cat-facts API.
URL : https://alexwohlbruck.github.io/cat-facts/docs/
and render the results with VueJS. What i found on the internet but this code just return some random numbers.
Here is the code:
created() {
this.getFacts();
},
methods: {
getFacts() {
let vm = this;
fetch('http://localhost:8080/facts')
.then(response => {
const reader = response.body.getReader();
return new ReadableStream({
start(controller) {
return pump();
function pump() {
return reader.read().then(({ done, value }) => {
// When no more data needs to be consumed, close the stream
if (done) {
controller.close();
return;
}
// Enqueue the next data chunk into our target stream
vm.facts = value;
controller.enqueue(value);
return pump();
});
}
}
})
})
.catch(err => console.error(err));
},
}
I am using vue.config.js to manage cors error:
module.exports = {
devServers = {
proxy: 'https://cat-fact.herokuapp.com/'
}
}
I made the request with POSTMAN and worked just well.
What happens if you do it like this:
async getFacts() {
let vm = this;
const response = await fetch('http://localhost:8080/facts');
const myJson = await response.json();
console.log(JSON.stringify(myJson));
}
Just wondring if you need to use pump at all.
EDIT
Without async/await
fetch('http://localhost:8080/facts')
.then(response => response.json())
.then(data => console.log(data));
I tried with ajax and a proxy made with php using guzzle to comunicate with the API and it worked! Just a simple line. But I am very confused about how fetch method works!
Forgive the ignorance, I'm not great with JavaScript (yet). I'm trying to fetch public user data from GitHub and display it on my personal portfolio. Currently I have the code below:
getData(url) {
return fetch(url);
}
const userData = getData("https://api.github.com/users/userName");
userData
.then((response) => response.json())
.then((response) => console.log(response))
.catch((error) =>
console.log("There was an error fetching the data: " + error)
);
console.log(userData)
The response I get is the JSON with the user data but when I console.log(userData) I get Promise { <state>: "pending" } as the response.
Also, I can see that there is an id in the initial response but when I console.log(userData.id) I get undefined.
I've read the GitHub API docs and watched a few videos on Promises but I can't seem to get my code to work correctly.
Thanks for taking the time to look at this and any help with this is greatly appreciated!
It is because userData is a promise. If you try using async/await (documentation is available here) you'll be able to synchronously get the data.
const getData = async (url) => {
try {
const data = await fetch("https://api.github.com/users/:user_name");
console.log(data.json());
return data;
} catch (e) {
console.log("There was an error fetching the data: " + error)
}
}
I have a requirement to display all the countries in the world in a drop down.
So I found this api end point END POINT LINK. When I copy and paste this end point link in my web browser I got a response with all the data. (countries);
When I try to embed this in project.
getCountries() {
try {
fetch(`https://restcountries.eu/rest/v1/all`).then(data =>
console.log(data)
);
} catch (error) {
console.log("HERE ERROR COMES", error);
}
}
It does go to then block of the fetch method. But gives me the output
There is nothing called data here. Even I get a success respond.
Why could this happen? Is this something related to cors errors?
You can use as follow:
let url = 'https://restcountries.eu/rest/v1/all';
fetch(url)
.then(res => res.json())
.then((data) => {
console.log(data);
})
.catch(err => { throw err });
This works for me
function getCountries(){
fetch("https://api.printful.com/countries ")
.then((resp) => resp.json()) // Transform the data into json
.then(function(data) {
let countries = data.result;
return countries.map(function(country){
console.log(country.name);
//Create your list here
});
});
}
responce.type 'cors' probably means Cross Origin Request - and it's blocking it - try to find another api