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