Answer the question
In order to leave comments, you need to log in
How to fix error while uploading a file using fetch?
There is a server on node.js, after I follow the link to another page, I need to load the data from the json file into an array in js, I do it through fetch (), I saw on YouTube how the code worked, but the server code was not shown on the video etc. Here is the js code itself:
fetch("./data.json")
.then(function(resp){
return resp.json();
})
.then(function(data) {
console.log(data);
});
const http = require("http");
const fs = require("fs");
http.createServer((req, res) => {
switch (req.url) {
case '/':
const html = fs.readFileSync('index.html', 'utf8');
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(html);
case '/exmpl.js':
const js = fs.readFileSync('exmpl.js', 'utf8');
res.writeHead(200, {'Content-Type': 'text/javascript'});
res.end(js);
case '/Gistograma.html':
const gist = fs.readFileSync('Gistograma.html', 'utf8');
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(gist);
case '/Gistogr.js':
const gistjs = fs.readFileSync('Gistogr.js', 'utf8');
res.writeHead(200, {'Content-Type': 'text/javascript'});
res.end(gistjs);
case '/server1.js':
const server1 = fs.readFileSync('server1.js', 'utf8');
res.writeHead(200, {'Content-Type': 'text/javascript'});
res.end(server1);
default:
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('ERROR 404');
}
}).listen(3000, () => console.log('server is on'));
Answer the question
In order to leave comments, you need to log in
First, your server must be able to process a request for '/data.json'.
In the back part code you provided, requests for: '/', '/exmpl.js', '/Gistograma.html', '/Gistogr.js', '/server1.js' are processed. And in the default block, instructions are generally indicated that if a request comes for something else that is not included in this list, then respond with a 404 code - the standard HTTP response code, if the requested resource is not found.
Thus, if you add something like the following, then the problem should be solved:
case '/data.json':
const js = fs.readFileSync('data.json', 'utf8');
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(js);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question