How can I query localhost server from my website with javascript? - 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!

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!

Related

Why is Node.js simple http server app not working on server?

I'm learning how to use Node.js apps in a server (not my local machine). In this situation, I'm following this tutorial in order to create a simple web server.
I have installed Node.js, and tested via CLI that it works. I can run javascript code, generate output in the CLI, etc. But I can't manage to make the an app work via URL using a browser.
The app folder structure I have is very simple:
index.js
package.json
package-lock.json
This is the code I'm currently working with in index.js:
var http = require('http'); // 1 - Import Node.js core module
var server = http.createServer(function (req, res) { // 2 - creating server
if (req.url == '/') { //check the URL of the current request
// set response header
res.writeHead(200, { 'Content-Type': 'text/html' });
// set response content
res.write('<html><body><p>This is home Page.</p></body></html>');
res.end();
}
else if (req.url == "/student") {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('<html><body><p>This is student Page.</p></body></html>');
res.end();
}
else if (req.url == "/admin") {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('<html><body><p>This is admin Page.</p></body></html>');
res.end();
}
else
res.end('Invalid Request!');
});
server.listen(5000); //3 - listen for any incoming requests
console.log('Node.js web server at port 5000 is running..')
If I go via CLI to the app's folder and run the app (node index.js), I can see the expected console.log() output (Node.js web server at port 5000 is running..). But if then I go to the URL pointing at that folder, which I would expect to output <html><body><p>This is home Page.</p></body></html>, it doesn't work (see below for what I get).
I have a domain (http://example.com) with document root in the app's folder. Here's what I have tried:
https://example.com //browser shows the source code of index.js
https://example.com:5000 //browser shows ERR_CONNECTION_TIMED_OUT
https://example.com/:5000 //browser show 404 error
https://example.com/index.js //browser shows the source code of index.js
https://example.com/index.js:5000 //browser show 404 error
None of those give the response I would expect. I don't know if this is a problem with my file structure, my server configuration... but I've been looking around and I can't figure why this basic example isn't working in my case, clearly I'm missing something. Any help would be much appreciated!
EDIT:
The server where I'm trying to run this app is a LAMP machine with CentOS 7.
I have checked in my server (Nginx), your code works fine.
After reading #MinusFour 's comment, I suspect that you didn't open 5000 port in your server's security groups.
Security Groups are like
If that not work, you can also check your server's firewall setting.
As for your domain expression:
https://example.com //browser shows the source code of index.js
https://example.com:5000 //browser shows ERR_CONNECTION_TIMED_OUT
https://example.com/:5000 //browser show 404 error (incorrect)
https://example.com/index.js //browser shows the source code of index.js
https://example.com/index.js:5000 //browser show 404 error (incorrect)
You can refer to https://support.google.com/gsa/answer/6329145?hl=en
I haven't got 50+ reputations to comment so I have to answer here.

How to access the Node server hosted in my laptop from a device in another network?

I have written this test.js
var http = require("http");
http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(8080,'192.168.1.5');
// Console will print the message
console.log('Server running at http://192.168.1.5:8080/');
I runned the command node test.js
C:\Users\ShalomAlexander\Documents>node test.js
Server running at http://192.168.1.5:8080/
This URL is accessible from my laptop and devices connected to the same wifi network. but I'm not able to access it when I switch from wifi network to mobile network on my smartphone.
so how can I make it work on other devices in different networks?
You need to either...
host your app on a public server (e.g. a cloud provider) or
make your machine publicly available
Second option requires you to do a port opening & proper forwarding from your router to your machine. Also, you probably want some dynamic DNS entry for your IP, because in general you're not having a fixed IP. Just some hints for this - I don't know what your use case is.
You need to host your NodeJs application on a server(eg: heroku). Then you can access it with the hosted URL.
Please check the documentation on deploying your NodeJs application in Heroku.
https://devcenter.heroku.com/articles/getting-started-with-nodejs

Angular on Node JS web service - GET http://127.0.0.1 net::ERR_CONNECTION_REFUSED

I am developing website using AngularJS and host it within NodeJS (Express JS) web service. The AngularJS uses the data on some endpoints served by NodeJS. In another word, the NodeJS has endpoints which serve AngularJS web page and providing data needed.
Before host the webpage on my virtual machine (web service), I use my host machine to host it. The webpage then tried to request the data to my virtual machine's endpoint and it works fine.
However, when I'm hosting it on my virtual machine (web service) and changed to request data on my localhost (http://127.0.0.1:3000/data), I am now getting GET http://127.0.0.1:3000/data net::ERR_CONNECTION_REFUSED error.
What I have tried
First, I thought it was occurred because of cross origin resource sharing, so I am enabling that in my NodeJS by adding these lines of code (taken from this site):
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
However, it still does not help at all. I am still getting the same error message.
Later, I thought it probably my firewall was blocking the access. I then turned off my firewall and it still failed to fix my problem.
I believe it happened because of my webpage trying to access endpoint on its localhost API, which should be overcome with CORS handling on my first attempt.
What is causing this exactly if it is not CORS? How do I overcome this issue? Any help would be appreciated.
Update: Node JS Route Code
var express = require('express');
var app =express();
app.use(express.static(path.join(__dirname, 'public')));
app.get('/admin/login/:user/:pass', function(appReq,appRes){
appRes.status(200).send('1');
appRes.end();
});
app.get('/*', function(appReq, appRes){
fs.readFile('./public/index.html', function(err,data){
if (err) {
appRes.writeHead(500);
appRes.end('Error loading html');
}
else {
appRes.writeHead(200);
appRes.end(data);
}
});
});
app.listen(port, function(){
console.log('express app listening at http://'+hostname+":"+port+'/');
});
Here is my AngularJS GitHub repo
Turns out using localhost IP is wrong. It is probably due to the JavaScript is sent to the client and the browser then interprets localhost is the client's localhost. Therefore, changing the localhost to my actual IP address solved my problem.

Unexpected Access-Control-Allow-Origin error

I'm following a simple tutorial from here:
http://addyosmani.github.io/backbone-fundamentals/
I have a node.js server running on a localhost port 4711
I have tomcat running on port 8082 and a backbone.js app as client started as index.html on that server.
But I get :
XMLHttpRequest cannot load ... api/books. Origin localhost:8082 is not
allowed by Access-Control-Allow-Origin.
1) Why? This is not file based access - indeed a plain web browser will see
htttp://localhost:4711/ and interact just fine.
2) What's the fix? (Given that part of this stack is a node.js server)
You're initiating a CORS request since the two servers are listening on different ports( index.html on localhost:8082 and your node server on localhost:4711)
In your node's http server, try setting the Access-Control-Allow-Origin header to * or to the Origin header.
http.createServer(function(req, res) {
res.header('Access-Control-Allow-Origin', req.headers['origin']);
//handle
});

Using node.js and express to process a POST request

I am new to learning AJAX and new to web development at all, and I am having trouble having my local server and my remote server process a post request. I am using node.js and the express module.
Here is the code of my server:
var express = require('express');
//start server
var app = express.createServer();
//handle requests
app.post('/hello', function(req, res){
res.send("hello");
});
app.listen(8888);
Pretty basic, I know. To test this, I create an XMLHttpRequest manually through the console in Chrome (I have disabled the Cross-Origin policy to test on my local machine):
var xhr = new XMLHttpRequest();
xhr.open('POST', 'localhost:8888/hello', true);
xhr.send('name=me'); //body of request is irrelevant at this point
When I send the request to my local machine, it returns immediately and says it failed. When I send the request to my remote server (where localhost is replaced by my server's IP) I don't get the error in my console, but when I check the xhr object's status is failed.
I don't know whether the problem is with the way my server is written, or the way I am sending the request to the server. However, I have been looking at tutorials and examples that show express processing post requests like I do above, and other tutorials that show sending POST requests like I do above.
Sending and processing GET requests seems to work fine. I must be missing something.
Thanks, Xaan.
You need to include HTTP in your URL when you issue the POST:
xhr.open('POST', 'http://localhost:8888/hello', true);
XHR does not work if the calling js is not served by a webserver.
What you should do is add a simple route on your Express server
app.get('/', function( req, res) {
res.sendfile('index.html');
})
Where index.html contains your testing code.
If you want to test from a different webserver and be confronted with the annoying Cross-Origin policy you can also use this super usefull command to spawn a webserver in your current folder:
python -m SimpleHTTPServer
I use it so often that I actually alias it:
alias www='python -m SimpleHTTPServer'

Categories