Dzmitry Dranitski
Dzmitry Dranitski

Reputation: 669

How can I query localhost server from my website with javascript?

I have a website running on, for example, mydomain.com. Then i am starting local backend server at localhost:3000 (127.0.0.1:3000). Can I add some js code to this website so it will query my local backend? Since my browser and my local backend are on same computer I guess it can access my local backend somehow. I tried creating a codepen https://codepen.io/dranitski/pen/ExNZLJo?editors=1111 with this code:

fetch('http://localhost:3000/').then(r=> r.json().then(j=> console.log('\nREQUEST',j)));

And created test.js file locally with content:

require('http').createServer(function (req, res) { res.end('' + process.pid); }).listen(3000);

then started it with node test.js

But my codepen gives me an error Uncaught NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'http://127.0.0.1:3000/'

I can claim backend is working since i can access http://127.0.0.1:3000/ from my browser and see the result successfully.

The idea behind that is to create a website that can interact with backend running locally on user's machine. My users have our backend server started locally and I need an online tool that can query these as well showing them some data from their local backends in human-readable form.

Thanks in advance!

Upvotes: 2

Views: 3911

Answers (1)

Dzmitry Dranitski
Dzmitry Dranitski

Reputation: 669

It works!

Just needed to enable cors on local node server

test.js

require('http').createServer(function(req,res){
    // Set CORS headers
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Request-Method', '*');
    res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
    res.setHeader('Access-Control-Allow-Headers', '*');

    res.end('' + process.pid);

}).listen(3000);

then run it with node test.js

Now the pen can access the server!

Upvotes: 4

Related Questions