Nodejs fails to show output on the cmd - javascript

I'm new to nodejs, All I'm trying to do is running a simple nodejs file on windows console Here's what I'm doing :
const http = require('http');
const host = '127.0.0.1';
const port = 3000;
const server = http.createServer(function(request, response) {
response.writeHead(200, {
'Content-Type': 'text/html'
});
response.end('Hello world');
}).listen(port, host);
server.on('connect', function(req) {
console.log(req.url);
console.log('Connected!');
})
server.on('error', function(e) {
console.log(e);
})
The file is stored on D:\nodjs\test directory when I navigate to this directory and run
the node hello.js command I'm expecting to see outputs ( response ) on the console.
However this is not happening, it just show a blank response, I wonder if it takes too long to load or anything else might be related with my client/port setup ?

Related

Firefox can’t establish a connection to the server at wss://localhost:8000/

I am using nodejs to run the server, there is no log file
This is my server.js
const https = require('https');
const fs = require('fs');
const ws = require('ws');
const options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};
const wss = new ws.Server({noServer: true});
function accept(req, res) {
// all incoming requests must be websockets
if (!req.headers.upgrade || req.headers.upgrade.toLowerCase() != 'websocket') {
res.end();
return;
}
// can be Connection: keep-alive, Upgrade
if (!req.headers.connection.match(/\bupgrade\b/i)) {
res.end();
return;
}
wss.handleUpgrade(req, req.socket, Buffer.alloc(0), onConnect);
}
function onConnect(ws) {
ws.on('message', function (message) {
let name = message.match(/([\p{Alpha}\p{M}\p{Nd}\p{Pc}\p{Join_C}]+)$/gu) || "Guest";
ws.send(`${name}!`);
//setTimeout(() => ws.close(1000, "Bye!"), 5000);
});
}
https.createServer(options, function (req, res) {
res.writeHead(200);
res.end("hello world\n");
}).listen(8000);
This is my code in react
componentDidMount() {
var connection = new WebSocket('wss://localhost:8000/');
connection.onopen = function(e) {
connection.send("add people");
};
connection.onmessage = function(event) {
// alert(`[message] Data received from server: ${event.data}`);
console.log("output ", event.data);
};
}
While I am trying to connect with web-socket with my jsx file its give me an error which is Firefox can’t establish a connection to the server at wss://localhost:8000/.
Your implementaion needs some changes. In the backend server, you forgot to call the onConnect function. So your ws.on method will never call.
Also, you imported the ws and create a WebSocket server wss, but you add some event listener on ws wrongly, you should add listener on your Websocket instance (wss):
// rest of the codes ...
const was = new ws.Server({noServer: true})
wss.on('connection`) {
// do something here ...
}
// rest of the codes ...
https.createServer(options, () => {
// do something here ...
})
There are some examples of how to create the WebSocket server along with the HTTP server on ws npm page.

How to make an HTTP/HTTPS request within a Node.js server?

I'm just starting to learn Node.js and right now, I'm trying to use a Node.js Application through cPanel to provide a JSON response when its app's URL is accessed.
When visiting the app's URL, it's evident that the Node.js server is working as it should. So after editing the main JS file, and restarting the Node.js app, changes are reflected when visiting the URL again.
My problem:
Within the function of https.createServer( function (req, res) {});, I want to make an HTTPS request to a PHP file elsewhere, which returns a JSON response. At the moment, I can't even get a response or error from any type of request with the PHP file.
var https = require('https');
var server = https.createServer(function (req, res) {
var message = "";
res.writeHead(200, {
'Content-Type': 'text/plain'
});
var options = {
host: "mydomain.com",
path: '/myPhpScript.php'
};
https.get(options, function(res) {
var bodyChunks = [];
res.on('data', function(chunk) {
bodyChunks.push(chunk);
}).on('end', function() {
var body = Buffer.concat(bodyChunks);
message += body;
})
}).on('error', function(e) {
message += e;
});
res.end(message);
});
server.listen();
As you can see, message would be what's displayed to the browser window, but it's empty. Nothing appears when visiting the App URL. Is it possible to make an HTTPS request with a Node.js HTTPS server?
Note:
I've also tried with native-request and axios and have experienced the same issue.
Server code:
var http = require('http');
var https = require("https");
var server = http.createServer(function (req, res) {
let call = new Promise((resolve, reject) => {
var options = {
host: "jarrenmorris.com",
port: 443,
path: '/gamesense/r6_db/1.json'
};
https.get(options, function (res) {
var bodyChunks = [];
res.on('data', function (chunk) {
bodyChunks.push(chunk);
}).on('end', function () {
resolve(Buffer.concat(bodyChunks));
});
}).on('error', function (e) {
reject(e);
});
});
call.then((data) => {
// do something here with the successful request/json
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end(data);
}).catch((err) => {
// do something here with the failure request/json
// res.write("ERROR:");
res.end(err);
});
});
server.listen(8081, "127.0.0.1", () => {
console.log(`Server listen on ${server.address().address}:${server.address().port} `);
});
Response:
{"name":"tim","age":"42"}
First thing i noticed, while i tried to run your code was, you cant establish a connection to your node.js.
The reason for this was you use the https module, but didnt specify an certificates/keyfiles. Skip this, and work with http till you get the result you want.
Then i wrapped you https request to the external api/file in a promise.
This allows a simple chaining and better readability of the code.
When the promises resolves/fullfill, we answer the request on the http server with the data we received from the external request.
The res.end in your code (where you put it) made no sense, since you didnt wait for the external request to complete. Thats the reason why its nothing is shown in the browser window.

Connect node app and server + post image to server

I have a very basic question about a node application, and a question about HTTP requests. It's the first time I create a node app with server, and I just can't seem to get the different components to work together.
This is my server.js
var express = require('express');
var multer = require('multer');
const request = require('request');
const upload = multer({dest: __dirname + '/uploads/images'});
const app = express();
const PORT = 3000;
app.use(express.static('public'));
app.post('/upload', upload.single('photo'), (req, res) => {
if(req.file) {
res.json(req.file);
}
else throw 'error';
});
app.listen(PORT, () => {
console.log('Listening at ' + PORT );
});
Then I have a file app.js with a motion-detection system. Every time motion is detected, a picture is taken. This all works fine.
Then the picture should be sent to the server. This is what I can't figure out.
I created a function toServer() that should post the detected data to the server
const request = require('request');
function toServer(data) {
const formData = {
// Pass data via Buffers
my_buffer: data,
// Pass optional meta-data with an 'options' object with style: {value: DATA, options: OPTIONS}
// Use case: for some types of streams, you'll need to provide "file"-related information manually.
// See the `form-data` README for more information about options: https://github.com/form-data/form-data
};
request.post({url:'http://localhost:3000/upload', formData: formData}, function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('Upload failed:', err);
}
console.log('Upload successful! Server responded with:', body);
});
};
Problem 1: when running the server.js on localhost:3000, it doesn't find any of the scripts loaded in index.html nor my app.js.
Problem 2: when running the index.html on live-server, all scripts are found, but i get the error "request is not defined".
I am pretty sure there is some basic node setup thing I'm missing.
The solution for toServer() might be more complicated.
Thanks for your time,
Mustard Shaper
Problem 1:
this could happen because you have not specified to render your index.html.
for example:
res.render('index')
if it's not because of the single quotes in upload.single('photo') try double quotes.
Another possible error could be that you are missing a default display engine setting.
an example: https://www.npmjs.com/package/hbs
Problem 2:
it may be because you are missing the header
var request = require('request');
request.post({
headers: {'content-type' : 'application/x-www-form-urlencoded'},
url: 'http://localhost',
body: "example"
}, function(error, response, body){
console.log(body);
});
See more at https://expressjs.com/

How to Send Streamed UDP Packets to Browser Using SSE in Node JS?

I have a node js server that listens to audio that is streamed on a local network using VBAN protocol. VBAN, basically a protocol that sends audio stream over local network using UDP. You can read more about VBAN and it's applications here
The next step, after receiving the audio from the VBAN, the node js server process the received audio.
Also, the node js server should send the processed packages to the browser, in this case, using EventEmitter, through a GET request:
const EventEmmitter = require("events");
const stream = new EventEmmitter();
app.get("/stream", function (req, res) {
res.writeHead(200, {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
});
stream.on("push", function (event, data) {
res.write(`event: ${event}, data: ${JSON.stringify(data)}`);
});
});
In the front-end side, which is an Angular application, receives the data from the server using EventSource
public dataObservable(): Observable<MessageEvent> {
return Observable.create((observer) => {
let eventSource = new EventSource('http://localhost:3000/stream');
eventSource.onmessage = (event) => {
console.log('Received event: ', event);
const json = JSON.parse(event.data);
console.log("audio", json);
observer.next(json);
};
eventSource.onerror = (error) => {
if (eventSource.readyState === 0) {
console.log('The stream has been closed by the server.');
eventSource.close();
observer.complete();
} else {
observer.error('EventSource error: ' + error);
}
};
});
}
From the inspector, in the Network, it shows that the browser is receiving the data from the server, but there is no data being emitted from the EventSource.
I'm not sure whether I'm using the wrong approach or I have the wrong implementation of this approach. I would appreciate your help.
I was able to send the processed packages to the front-end side using Socket IO.
Here's the server-side implementation (node js):
first of all, I installed socket.io dependency into node js app:
npm install socket.io
Then, to initialize the socket.io:
var express = require("express");
var app = express();
const http = require("http").createServer(app);
const io = require("socket.io")(http);
And here I've configured the HTTP get request, and make the app listing to the specified port:
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:4200");
res.header("Access-Control-Allow-Credentials", true);
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
app.get("/", (req, res) => {
res.send("<h1>Hey Socket.io</h1>");
});
http.listen(3000, () => {
console.log("Server running on port 3000");
});
Next, emitting the audio messages using the socket.io
io.on("connection", (socket) => {
console.log("a user connected");
socket.on("disconnect", () => {
console.log("user disconnected");
});
});
io.on("connection", () => {
let dgram = require("dgram");
let server = dgram.createSocket("udp4");
server.on("listening", () => {
let address = server.address();
console.log("server host", address.address);
console.log("server port", address.port);
});
server.on("message", function (message, remote) {
let audioData = vban.ProcessPacket(message);
io.emit("audio", audioData); // // console.log(`Received packet: ${remote.address}:${remote.port}`)
});
server.bind(PORT, HOST);
});
In the front-end (Angular):
I've added socket.io dependency into the Angular app:
npm install socket.io-client
Finally, I've added a listener for my audio event:
export const environment = {
production: false,
SOCKET_ENDPOINT: 'http://localhost:3000'
};
setupSocketConnection() {
var socket = io(environment.SOCKET_ENDPOINT);
socket.emit('my message', 'Hello there from Angular.');
socket.on('audio', (audio) => {
console.log('audio:' ,audio);
this.playAudio(audio);
});
}
Reference to the source which I've used to implement the socket.io
I still want to know if I can use EventEmitter to send the data to the client app.

Node.js Server crashed when Refresh Browser

I tried to build a chat box server by node.js. When the browser requestes the page, it workes well at first. But when I refresh the page, the Server crashes.
Below is the error message:
events.js:183
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at _errnoException (util.js:1022:11)
at TCP.onread (net.js:615:25)
I used the node --inspect index.js, but could not find the point.
Below is the code of index.js:
const http = require('http');
const fs = require('fs');
const extract = require('./extract');
const wss = require('./websockets-server');
var handleError = function (err,res) {
res.writeHead(404);
res.end();
}
var server = http.createServer(function (req, res) {
console.log("Responding to a request.");
var filePath = extract(req.url);
console.log("filePath:"+filePath);
fs.readFile(filePath,function (err,data) {
if(err){
handleError(err,res);
return;
}else {
res.end(data);
}
})
})
server.listen(3000);
When I comment the 4th line, the import of websockets-server. Server works well when I refresh the page. Maybe it's about the websocket while it works without websocket.
Below is code of websockets-server.js:
const WebSocket = require('ws');
var WebSocketServer = WebSocket.Server;
var port = 3001;
var ws = new WebSocketServer({
port:port
});
var message = [];
console.log('websockets server started');
ws.on('connection', function (socket) {
console.log('client connection established');
message.forEach(function (msg) {
socket.send(msg);
})
socket.on('message', function (data) {
console.log('message received: ' + data);
message.push(data);
ws.clients.forEach(function (clientSocket) {
clientSocket.send(data);
});
});
});
Does the problem is about the websocket? Whether should I do process when the client shutdown the connection with the server while refreshing the page.
extract.js below:
const path = require('path');
var extractFilePath = function (url) {
var filePath;
var fileName = 'index.html';
if(url.length > 1){
fileName = url.substring(1);
}
console.log('The fileName is: ' + fileName);
filePath = path.resolve(__dirname, 'app', fileName);
return filePath;
}
module.exports = extractFilePath;
I guess that you maybe execute var ws = new WebSocket("ws://localhost:3001"); in html file. I haven't figured out exact reason about your error as I'm not proficient in WebSocket. But there is a solution:
window.onbeforeunload = function () {
ws.close();
}
close connection before reload, then the error will not reappear.
You need to add an error listener on the socket. Error listener only on the websocket instance does not help in this case.
socket.on('error', function(e){
console.log(e);
});
The ECONNRESET error means that the other side (browser) closed the connection abruptly. On browser refresh, browser simple killed the connection with the websocket server.
To solve this, you have to listen for the error event on the websocket server instance.
// listen for "error" event so that the whole app doesn't crash
wss.on("error", function(error){
console.log(error);
}
I was having the same problem, but it resolved after this command:
npm install #ionic/app-scripts#nightly --save-dev

Categories

Resources