0

This is my server in Node.js

var http = require('http'),
    fs = require('fs');

http.createServer(function(req, res) {

    if(req.url == '/req_to_node') {
        res.writeHead(200);
        if(fs.existsSync(__dirname+'/file1.json')) {
            fs.readFile('http://example.com/file2.json', (err, contents) => {
                res.end(contents.toString());
            });
        }
    }

    fs.readFile(__dirname+'/index.html', (err, contents) => {
        res.writeHead(200);
        res.end(contents);
    });

}).listen(80, 'localhost');

And this is code of my index.html

<script>
ajaxReq('req_to_node', function(result) {
    if(result != '') {
        console.log(result);
    }
});

function ajaxReq(slug,callback) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'http://localhost/'+slug);
    xhr.send();
    xhr.onreadystatechange = function() {
        if(this.readyState == 4 && this.status == 200) {
            callback(this.responseText);
        }
    };
}
</script>

As you see, with XMLHttpRequest on the client I'm trying to check if local file1.json exists and if yes, trying to read content of another file2.json which is online (on my own domain).

But in console I get the error

GET http://localhost/req_to_node net::ERR_CONNECTION_RESET

While if I switch the file reading to the same local file1.json instead of the online file2.json, it works i.e.

...
fs.readFile(__dirname+'/file1.json', (err, contents) => {
...

ps. I'm interested in a solution without Express, if it's possible

stckvrw
  • 1,689
  • 18
  • 42
  • 3
    the `fs` module is for interactive with the local file system and can't make network request, to get the conents of `http://example.com/file2.json` look at the `http` module example here: https://stackoverflow.com/questions/38284765/get-file-from-external-url-with-fs-readfile – dotconnor Nov 21 '18 at 21:06
  • Can I do it only with Express or without as well? – stckvrw Nov 21 '18 at 21:10
  • 1
    No, you can use it without as well, `http.get("http://example.com/file2.json", (contents) => { contents.pipe(res); });` – dotconnor Nov 21 '18 at 21:14
  • @dotconnor thank you! One more question: how to handle errors so that if the online `file2.json` is not accessed, the code would be getting local `file1.json` ? – stckvrw Nov 25 '18 at 20:34

0 Answers0