Im new to node js.
const http = require('http');
const url = require('url')
http.createServer(function (req, res) {
const { query, pathname } = url.parse(req.url, true)
let answer =[];
async () => {
await fetch('https://dummyjson.com/products').then(r => r.json()).then(d => {
answer.push(JSON.stringify(d))
})
}
res.writeHead(200, {
"Content-Type": 'text/html',
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "X-Requested-With"
});
res.end(answer);
}).listen(8080);
console.log('Server Started');
Im trying to save the data in my array, once i get the info i should be able to render all data from that api.
CodePudding user response:
You have several issues:
- Your async IIFE with the
fetch()
in it is never called. - Even if it was called, you wouldn't be waiting for it. You are trying to send your response before the
fetch()
has completed. - You are trying to send an array (that has JSON in it) with
res.end()
. You can't do that. You need to send text. - You are setting the content-type to text/html, but attempting to send JSON. If you're actually going to send JSON, then set the content-type to
application/json
.
Change to this:
const http = require('http');
const url = require('url')
http.createServer(async function (req, res) {
const { query, pathname } = url.parse(req.url, true)
const answer = [ ];
const r = await fetch('https://dummyjson.com/products');
const data = await r.json();
answer.push(data);
res.writeHead(200, {
"Content-Type": 'application/json',
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "X-Requested-With"
});
res.end(JSON.stringify(answer));
}).listen(8080);
console.log('Server Started');
Summary of Changes:
- The callback to
http.createServer()
is marked asasync
so we can directly useawait
in that callback function. - Remove
.then()
and just useawait
. Don't mixawait
and.then()
. Pick one style or the other. - Push Javascript data, not JSON into the array.
- Call
JSON.stringify()
on the whole array. You can pass an array tores.end()
, you have to pass text. - Change content-type to
application/json
.