Localhost refuses connection from Javascript - javascript

I am making a single web app that takes information from MYSQL database and displays it on screen using AngularJS and NodeJS. I have set up a node.js server that gives out JSON file from a database. It works fine if I connect to it like this: 192.168.1.57:8888 which is my home server ip or remote connecting my server and using localhost:8888. Doing this downloads the JSON file on my computer.
However. If I'm using javascript to get JSON file from the server it gives me this error:
GET http://localhost:8888/ net::ERR_CONNECTION_REFUSED
I have tried connecting to the server with both AngularJS and JQuery and they both give the same error. I've also tried 127.0.0.1 and that doesn't work either. What can I do to fix it or can I do this with a better alternative way?
This is the server code in node.js
var http = require("http");
mysql = require("mysql");
var connection = mysql.createConnection({
user: "test",
password: "test",
database: "test"
});
http.createServer(function (request, response) {
request.on('end', function () {
connection.query('SELECT * FROM feedback;', function (error, rows, fields) {
response.writeHead(200, {
'Content-Type': 'x-application/json'
});
response.end(JSON.stringify(rows));
});
});
}).listen(8888);
this is the client side in angularJS:
(function(){
var app = angular.module('question', [ ]);
app.controller("ServerController", [ '$http', function($http){
$http.get("http://localhost:8888").success(function(data,status,headers,config){
console.log("success");
}).error(function(data,status,headers,config){
console.log("error");
});
} ]);
}
)();

Taking a guess at it, you're running into the Same Origin Policy, which requires that the page making the ajax request be in the same origin as the resource it's requesting (or that the server serving the resource supports CORS and allows the page's origin).
Two different ways this might be hitting you (I can't tell which, the question doesn't give enough information):
If the browser code is running in a page loaded from the file system, not via HTTP, then it's a cross-origin request because the protocols don't match (file: vs. http:).
If the page has not been loaded from localhost:8888, but instead from some other port on localhost, then the origins don't match because the port numbers are different.

Related

Rest API based TCP client using Node js

I have tried to create TCP Client with rest api using nodejs and also used net module to establish tcp connection to send/receive data. The main idea is to use this restAPI from browser to load test TCP Connections.
Here in my case there are 2 steps involved while load testing TCP.
1) send initial TCP request which has token for authentication.
2) then send other TCP request to send some data.
The issue is when i try to send 2nd TCP request after authentication. Getting response as invalid session.
Please suggest if i can send TCP request for authentication and using same session/connection while making subsequent requests.
I am new to node js. My Apologize if I have not provided enough details or done some thing invalid.
Initially I have used Packet Sender application and enabled persistent TCP Connection option in it. It worked well as expected but this is for single user and cant use this tool for load testing. Here in this tool with persistent TCP enabled I can see the local port is fixed and not changing upon sending multiple requests but with my node js code i can see the local port is getting changed upon every new request.
I have also used TCP Sampler in Jmeter with reuse Connection option but not working when i send 2nd request after authentication.
var Net = require('net');
var express = require("express");
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.post('/api/push', function (req, res) {
var reqBody = req.body.reqBody;
var req = JSON.stringify(reqBody);
const client = new Net.Socket({
allowHalfOpen: true
});
client.connect({
port: req.body.port,
host: req.body.host
}, function () {
client.write(req);
});
client.on('data', function (chunk) {
res.write(chunk.toString());
//Tried to use client connection information, but didnt worked not sure if i missed something.
console.log(JSON.stringify(client));
// Tried commenting below client.end but no luck.
client.end();
});
client.on('end', function () {
res.end();
});
client.on('error', function (err) {
console.log("Error: " + err.message);
res.write(err.message);
client.end();
});
});
app.listen(1234, () => {
console.log("Server running on port 1234");
});
1) send restAPI with TCP server host/port and request body for authentication.
2) send another restAPI to use same TCP connection and send data. but it failed for mere
Inspect the behavior and get the cookies details and preserve the same in HTTP cookie manager to reuse the same session for the second request. Just adding http cookie manager also might work. Please check,

Nodejs HTTP Createserver - unpredictable javascript execution while serving from html files

When I serve an html file, having some javascript, from my nodejs web server I get different results, compared to when I include the same javascript from an external source. I have verified that directly opening the html file with the javascript inline or external source works the same, as expected.
In the example below I get "Modified header" in h1 tag, whereas with javascript as external source I get "Unmodofied header" in h1 tag.
Can somebody explain how to rectify the problem? Thanks.
Code for nodejs web server:
var http = require('http')
var fs = require('fs')
http.createServer(function (request, response) {
fs.readFile('htmlfile.html', function(err, data) {
response.writeHead(200, {'Content-Type': 'text'})
response.write(data)
response.end()
})
}).listen(8081)
htmlfile.html is as follows:
<html>
<body>
<h1 id = "header"> Unmodified header</h1>
<!-- <script src="populate_header.js"></script> -->
<script>
function populate_header () {
document.getElementById("header").innerHTML = "Modified header"
}
populate_header ()
</script>
</body>
</html>
In a nutshell, your http server is not configured to send populate_header.js to the browser when the browser asks for it.
When you do this in your HTML file:
<script src="populate_header.js"></script>
You're telling the browser to send your web server a request for a resource named populate_header.js. But your web server does not have a request handler that looks at what file is being requested and serve that specific resource. Your web server always sends htmlfile.html no matter what resource is being requested. So, the browser asks for a script file and gets an HTML file (causing it to basically just ignore it). Thus, your Javascript in populate_header.js is never delivered to the browser and thus the script in it never runs.
When you include the script inline, the Javascript is delivered with the HTML and works just fine without requiring another route on your web server.
A node.js web server serves NO files at all by default. It only serves files that you create a route handler for. It is possible to create a single route that will serve lots of static files (when using the Express framework, express.static() does exactly that). But, by default, it does not serve any files.
As soon as you need more than one route handler, I would recommend using a very simple framework like ExpressJS because it will save you a lot of time and is very lightweight. But, if you were going to add a new route handler to your existing little web server, you could do so like this:
var http = require('http')
var fs = require('fs')
http.createServer(function (request, response) {
if (request.method === "GET") {
let fname;
// Look at what resource was requested and match that up
// with the appropriate file name
// DO not accept any resource requested because that could open up
// your server for people to request your actual server code files
switch(request.url) {
case "/":
fname = "htmlfile.html";
break;
case "/populate_header.js":
fname = "populate_header.js";
break;
default:
break;
}
if (fname) {
fs.readFile(fname, function(err, data) {
if (err) {
response.writeHead(404);
response.end();
} else {
response.writeHead(200, {'Content-Type': 'text'})
response.write(data)
response.end();
}
});
} else {
response.writeHead(404);
response.end();
}
}
}).listen(8081)
Here, you can see you're looking at request.url to see what exactly was requested and then sending that resource. It's also looking a request.method to only respond to GET requests. And, it's sending 404 responses when some other file is sent.
This would all be a lot simpler using the ExpressJS framework.
const express = require('express');
const app = express();
// look for matching static resources in the static_files subdirectory
app.use(express.static("static_files"));
// send the htmlfile.html file when / is requested
app.get("/", function(req, res) {
res.sendFile("static_files/htmlfile.html");
});
app.listen(8081);
Then, just locate all your static resources in a sub-directory below your main server directory named static_files and the Express framework will automatically look in that sub-directory for files that match the requested URL. This code adds one custom route for / that specifically sends the htmlfile.html file, and you can certainly customize that however you want.
For further discussion of how node.js servers don't send any files by default, see these other related answers:
Can't load local files when using NodeJS server
Resources not loading in express
ajax request gives a 404 with express server (chrome) loads successfully with firefox without a server?
How to get files above the server directory in Node.js

how to make a request to Ldap with client-side Javascript?

I should make a request to LDAP client side possibly with Javascript.
I searched in the web finding ldapjs that does what I want, but server side. This:
var ldap = require('ldapjs');
var server = ldap.createServer();
server.search('o=example', function(req, res, next) {
var obj = {
dn: req.dn.toString(),
attributes: {
objectclass: ['organization', 'top'],
o: 'example'
}
};
if (req.filter.matches(obj.attributes))
res.send(obj);
res.end();
});
server.listen(1389, function() {
console.log('LDAP server listening at %s', server.url);
});
So I tried using requirejs to import a library ldapjs client side, but was unable to make it work. There is no file called ldapjs to import.
I'm on the right track?
There are other ways?
I'm forced to stay on the client side
As long as you want to run your JavaScript in a web browser, you are limited to the HTTP protocol and to the domain from which your script was loaded in the first place.
So, talking to an LDAP server will not be possible from a web browsers JavaScript engine.
For do that install node.js and run your application locally.
use ldapjs to running in node to access the LDAP server and expose it to your standard http requests ( example: browser makes http request -> NodeJS runs LDAP JS Client---> connects to LDAP Server.)

Nodejs http server cannot handle, proxy enabled request from Amazon Load balancer

I have a nodeja HTTP server which was woking good until I enabled Proxy at amazon Load balancer (which is on TCP protocol) to get client's IP.
I wonder How TCP server of nodejs works perfectly , but http server cannot
var net = require('net');
var proxy_protocol = require('node-proxy-protocol');
net.createServer(function(socket) {
proxy_protocol.parse(socket, function(error, obj) {
console.log(obj); //returns required client's info
});
});
but, why http server fails to do , if I replace "net" with "http":
This does not work
var net = require('http');
var proxy_protocol = require('node-proxy-protocol');
http.createServer(function(req,res) {
proxy_protocol.parse(req, function(error, obj) {
console.log(obj); //returns nothing
});
});
although I know that HTTP (usually) operates over TCP, so it must work for both.
basically I think, My Http Server is not able to handle TCP request from Load Balancer.
Please let me know where am I going wrong.
My nodejs HTTP server was not handling TCP from Load Balancer, so I switched Load Balancer's Protocol to HTTP.and now my HTTP server works well.

Connect client to Node.js server with HTTP(S)

Users 'gather' data on their local pc, and they need to be able to upload it to the server.
I setup a simple node.js server like this:
var https = require('https');
var fs = require('fs');
var path = require('path');
var options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};
var server = https.createServer(options, function (request, response) {
response.writeHead(200, {'Content-Type': 'text/bold'});
response.end("Server is running");
});
Now I want to connect a client to it, using a httprequest. I tried JQuery/XMLhttpRequest but I get Cross-origin resource sharing errors (which I get why but I think I don't really want to disable this protection). I think it's possible to use sockets to establish the connection but I'm not sure if that would be a good choice. I'd rather want to work with HTTP requests.
var xmlhttp, text;
xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', 'http://localhost/file.txt', true);
xmlhttp.send();
//JQuery get
$.get("http://127.0.0.1:1337")
Anything missing? Feel free to ask.
Change http:// to https:// in your second set of code. Same-origin includes scheme/protocol. (And your server code appears to only be spinning up an https listener anyway. :) ).
Just a hint : If your client application page which is taking to your server is not rendered from the same domain where your server component is running then you will get such errors. This error means your page is going to access resources from another server, not from the server it is originated. All the browsers have such restriction. You can configure on you server to allow access form other domains (domain where your client app is hosted) or host both client app and server from same domain.

Categories

Resources