Node.js how to get http message (request, response) from net server (tcp server)? - node.js

I have the following code :
var net = require('net');
var fs = require('fs');
var path = require('path');
path = path.join(__dirname, 'index.html');
var fileAsAstream = fs.createReadStream(path);
var server = net.createServer(function (socket) {
socket.write("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: 10\r\n\r\n");
fileAsAstream.pipe(socket);
console.log("server is up. port 8081");
});
server.listen(8081);
index.html
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
(1) Why does chrome make two connections to the server when I try http://localhost:8081 ? How can I make it work with one connection? And how I can format the html file in the browser during this tcp server.
or if there is something that can help me.
(2) It just reads the html file one time when I try to make two connections at telnet.
HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 10
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
Connection to host lost.

Related

routing a webpage error, nodejs and expressjs

I am trying to route directly to the html file using express.js, getting an unknown error, being new to express.js, I couldn't get how to resolve this one:-
here is the js code :-
const express = require('express');
const path = require();
const app = express();
const port=process.env.PORT || 8000;
// public static path
const static_path = path.join(__dirname,"../public");
app.use(express.static(static_path));
app.get("",(req,res)=>{
res.send("welcome to this main page");
})
app.get("/about",(req,res)=>{
res.send("welcome to this about page");
})
app.get("/weather",(req,res)=>{
res.send("welcome to this weather page");
})
app.get("*",(req,res)=>{
res.send("404 Error page oops");
})
app.listen(port,()=>{
console.log(`listening to the port ${port}`);
})
static web page:-
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Weather App</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<h1>Welcome to the static web</h1>
</body>
</html>
getting this error:-
internal/validators.js:124
throw new ERR_INVALID_ARG_TYPE(name, 'string', value);
^
TypeError [ERR_INVALID_ARG_TYPE]: The "id" argument must be of type string. Received undefined
ok, I was using "type nul > filename" command for creating new files in attached folders. When I used directly the VSCode feature of creating files, it's working fine now,... don't know why, but I think that old command might have expired, tell me if I am wrong, but I just solved my issue...

How to re-translate image from other website (hiding source URL)

I have a link to the image like
this or that.
I'm trying to re-translate this image from other source URL to some link, f.e http(s)://examplewebsite.com/john.
So, it doesn't need to be a redirect, but rather "showing" image on a different link. I've tried using express.static but it doesn't work.
Thanks in advance
If I understand it right, you have your express server and you want to include foreign images in response while hiding source url
In the simplest form, every time someone requests your page, you would fetch the image you want, encode it in base64 and include this base64 as src for the img
const express = require('express')
const fetch = require('node-fetch')
const app = express()
const port = 3000
app.get('/', (req, res) => {
fetch('https://www.gravatar.com/avatar/fdb4d2674d818861be4a4139469ebe59?s=48&d=identicon&r=PG&f=1')
.then(res => res.buffer())
.then(buffer => {
res.send(`
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<p>hello</p>
<img src="data:image\png;base64, ${buffer.toString('base64')}" alt="image">
</body>
</html>
`)
})
})
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
ideally you would create a separate endpoint for these images and also cache them (in memory or on hard drive) to not re-download them every time you need them

Uncaught SyntaxError: Unexpected token < for JavaScript files

I am developing a MEAN stack CRUD project . After build my project I am getting this error from index.html file in dist/ngAppVideos/index.html folder.i tried <base href="/"> but no luck.
This is my index.html file
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>NgAppVideos</title>
<base href="/ngAppVideos/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
<script type="text/javascript" src="runtime.js"></script>
<script type="text/javascript" src="polyfills.js"></script>
<script type="text/javascript" src="styles.js"></script>
<script type="text/javascript" src="vendor.js"></script>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
This is server.js file
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const api = require('./server/routes/api');
const port = 3000;
const app = express();
api.use(express.static(path.join(__dirname, 'dist')));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/api', api);
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/ngAppVideos/index.html'));
});
app.listen(port, function () {
console.log("Server running on localhost:" + port);
});
I tried many ways like modifying base-href location in index.html file but didn't work
in my server.js I changed my __dirname to dist/index.html but this time it just prompt No such directory can be found..error.
Thanks!
you have a few mistakes:
1)for set public file to dist must be set the full path of dist.maybe is there in a subdirectory or anything like this.
2)in your node.js code, you tell return all GET request by an HTML file and in front-end code, you get a javascript file but your server code sends an HTML file and front-end wait for javascript code but get HTML file and send you this error.
to solving these problems must be set a correct public folder and put your javascript file to it and change get javascript path in front, for example
set public like this:
app.use(express.static(path.join(__dirname, 'subdirectory/dist')))
and change script tag to:
<script type="text/javascript" src="/runtime.js"></script>
don't forget put your javascript file in dist folder

Autobahn - Sent non-empty 'Sec-WebSocket-Protocol' header error

I am trying to build a WAMP server using NodeJS, wamp.io, and websocket.io.
Here is the server-side code :
var wsio = require('websocket.io');
var wamp = require('wamp.io');
var socketServer = wsio.listen(9000);
var wampServer = wamp.attach(socketServer);
And I am trying to test the pub-sub via browser using AutobahnJS. Here is the client-side code :
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Wamp Example</title>
</head>
<body>
<ul class="pages">
<li>
<button id="socket">Call</button>
</li>
</ul>
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="https://autobahn.s3.amazonaws.com/autobahnjs/latest/autobahn.min.jgz">
</script>
<script>
AUTOBAHN_DEBUG = true;
</script>
<script>
var connection = new autobahn.Connection({
url: 'ws://localhost:9000/',
realm: 'realm1'
});
console.log(connection);
connection.onopen = function (session) {
console.log(session);
// session is an instance of autobahn.Session
};
connection.onclose = function(reason, detail){
console.log(reason);
}
connection.open();
</script>
</body>
</html>
But the connection always got this error :
WebSocket connection to 'ws://localhost:9000/' failed: Error during WebSocket handshake: Sent non-empty 'Sec-WebSocket-Protocol' header but no response was received
This part of code return 'unreachable'
connection.onclose = function(reason, detail){
console.log(reason);
}
Is there any code I missed?

Client disconnects immediately after connection to Node js TCP server

This is my first time with node js. I am trying to get the client to connect to the server and maintain the connection without closure.
This is all hosted in an ubuntu server edition hosted in a virtualbox.
I had checked that the server is actually listening to the port 5000 using
netstat -ant
Websockets is also available on my browser.
I get the following output with error
Echo server dot come
192.168.1.107
node.js:134
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: EPIPE, Broken pipe
at Socket._writeImpl (net.js:159:14)
at Socket._writeOut (net.js:450:25)
at Socket.write (net.js:377:17)
at Socket.ondata (stream.js:36:26)
at Socket.emit (events.js:81:20)
at Socket._onReadable (net.js:678:14)
at IOWatcher.onReadable [as callback] (net.js:177:10)
and if i call socket.end() on the server on connection event handler i get a disconnecting client. My question is how to establish a stable connection using this code, what do i have to change or i am doing wrong here? pulling my hair out - thanks in advance!
HTML CODE
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Test RS Server (built over nodejs)</title>
<link rel="stylesheet" href="style.css"></link>
<script src="jquery.min.js" ></script>
<script src="client.js" ></script>
</head>
<body>
<label>Message</label>
<input type="text" id="message_box"></input>
<input type="button" id="submit_btn" value="Send"></input>
<div style="clear:both;"/>
<label>Output</label>
<textarea rows="10" cols="100" id="output_box"></textarea>
</body>
</html>
CLIENT JS
var message_box;
var output_box;
var submit_btn;
var url = "wss://192.168.1.107:5000";
var socket;
function createListeners() {
if ("WebSocket" in window) {
output_box.html("Supports sockets.");
socket= new WebSocket(url);
socket.onopen= function() {
socket.send("con opened");
output_box.html("Connection opened.");
};
socket.onmessage= function(response) {
// alert('got reply '+s);
console.log(response);
output_box.html(response);
};
socket.onclose = function() {
// websocket is closed.
output_box.html("Connection is closed...");
};
submit_btn.click(function(e) {
socket.send(message_box.val());
});
} else {
output_box.html("doesnt support sockets");
};
};
$(document).ready(function() {
message_box = $("#message_box");
output_box = $("#output_box");
submit_btn = $("#submit_btn");
createListeners();
});
SERVER JS CODE
var net = require('net');
var server = net.createServer(function (socket) {
socket.write('server says this\r\n');
socket.pipe(socket);
});
server.on('connection', function(socket) {
socket.write("Echo server dot come\r\n"+socket.address().address);
console.log("Echo server dot come\r\n"+socket.address().address);
// socket.end();
socket.pipe(socket);
});
server.listen(5000);
You are trying to use WebScoket client with simple TCP server. This is a different protocols. You need to setup WebSocket server to make it work. You can use websocket module to do that. Look at the server example code here.

Resources