Nodejs: simple code works on local but not on server - javascript

I am still learning node but there's one thing that I can't find answers anywhere.
I am trying to deploy a simple code to read the content of a URL. It works fine on localhost but when I deploy to my azure app it does not work at all.
When I access the link on the browser it shows a blank screen.
Here's the code
var http = require('http');
var server = http.createServer(function(request, response) {
const url = "http://www.google.com";
response.writeHead(200, {"Content-Type": "text/plain"});
http.get(url, res => {
res.setEncoding("utf8");
let body = "";
res.on("data", data => {
body += data;
});
res.on("end", () => {
console.log("End of response", port);
response.end('End of response.<br/>');
});
});
});
var port = process.env.PORT || 1337;
server.listen(port);
console.log("Server running at http://localhost:%d", port);

When I access the link on the browser it shows a blank screen.
I encountered the similar issue before, I tried to access http://cn.bing.com, but the request would be automatically redirected to https and there is no any response content.
Based on your code, I created my azure web app to check this issue.
app.js:
var http = require('http');
var server = http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
http.get("http://www.google.com", res => {
//check the status code
console.log(res.statusCode+','+res.headers['location']);
res.setEncoding("utf8");
let body = "";
res.on("data", data => {
body += data;
});
res.on("end", () => {
console.log("End of response", port);
response.end(body);
});
}).on('error',(e)=>{ //catch the error
console.error('Got error:'+e);
response.end('Got exception:'+e);
});
});
var port = process.env.PORT || 1337;
server.listen(port);
console.log("Server running at http://localhost:%d", port);
My project contents look like this via KUDU.
TEST:
For verifying the logs, you could Enable diagnostics logging and check your application logs. Also, you could add a iisnode.yml file into your web app root folder and specific your log configurations, details you could follow Debug Node.js Web Apps on Azure.
Additionally, here are some related tutorials, you could refer to them:
http.get(options[, callback])
How to deploy a node.js site into Azure Web App to create a Website
Create a Node.js web app in Azure

Related

VS code displays listing directory instead of serving the html file

I wanted to serve the Disp.html file through nodejs following the code I learned through a Youtube tutorial.
const http = require("http");
const fs = require("fs");
const fileContent = fs.readFileSync("Disp.html");
const server = http.createServer((req, res) => {
res.writeHead(200, { "Content-type": "text/html" });
res.end(fileContent);
});
server.listen(80, "127.0.0.1", () => {
console.log("Listening on port 80");
});
I have created a folder in VS Code with this app.js and Disp.html as the files. Every time I run the code it displays the listing directory in place of the HTML content that I am expecting to view.
What can I do to get the expected result?
Thanks, I got it. The local host was at port 5500 not 80, changing that in the code got me the html file served.
So it was server.listen(5500, ...)

Client program for continuous talking to an echo server in nodejs

I'm an absolute beginner in nodejs. I've created an echo server in nodejs. And honestly i would say, i followed few youtube tutorials for this. There is nothing wrong with the server code. I want to create a client program to talk to this server. I dont want to use telnet client or any such thing. And by 'continuous' I mean the server and client should stay connected till I close the server manually using ctrl+c. Here's my server.js.
const express = require('express');
const bodyParser=require('body-parser');
var server=express();
server.use(bodyParser.urlencoded({extended: false}));
server.use(bodyParser.json());
server.post("/", function (req, res) {
console.log("I got: "+req.body.message);
res.send(req.body.message);
});
server.listen(3000, function() {
console.log("Express echo server is listening on port 3000");
})
I do not say hey write the code for me. In fact I tried also. Here's my client.js
var request = require('request');
var arg="";
process.argv.slice(2).forEach(function (val, index, array) {
arg+=val +" ";
});
request.post({
url: "http://localhost:3000",
json: true,
body: {message: arg}
}, function (err, response, body) {
if(!err && response.statusCode==200) {
console.log(body);
}
});
But client sends data only once that too using command line argument.
node client.js hello
PS: I'm using these npm modules express, body-parser and request
What you made is a HTTP Server using express.
The server runs alright, but the client closes because you are only making a single request to the server. So what is happening is expected behaviour.
So, there are multiple ways,
The most simple way would be, using readline or some other to continuously read the lines that you type And sending it to the server:
const request = require('request');
const readline = require("readline").createInterface({
input: process.stdin,
output: process.stdout
});
readline.setPrompt('msg: ');
readline.prompt();
readline.on('line', function(input) {
if(input === 'close') return readline.close();
request.post({
url: "http://localhost:3000",
json: true,
body: {message: input}
}, function (err, response, body) {
readline.prompt();
});
}).on('close', function() {
console.log('Closed');
process.exit(0);
});
But the proper way would be using sockets like socket-io to make a persistent connection between the server and client. Read here for more information.

My HTML page is not the same when i launch with NodeJS

I would like to know why is there a difference when I launch my project with NodeJS and when I launch directly with the HTML file.
Here is what I am supposed to have (with the HTML file) :
And here is what I have through NodeJS :
As you can see, it seems that the VueJS variable is not working anymore.
I don't know why because, i just create a short NodeJS program to launch this HTML file. I know that it is not a huge problem and can be easily solved.
Here is my JS program
var http = require ('http');
var fs = require('fs');
var port = 3000
var server = http.createServer(function(req,res){
res.writeHead(200,{'Content-Type': 'text/html'})
fs.readFile('index.html', function(error,data){
if (error) {
res.writeHead(404);
res.write('Error file not found');
}else {
res.write(data);
}
res.end();
})
})
server.listen(port,function(error){
if(error){
console.log('Something went wrong', error);
}else {
console.log("server is listening on port 3000");
}
})
Thank you guys in advance for your help. I look forward to see your responses.

Javascript Websocket server message broadcast to clients

I am trying to create a dummy websocket server in javascript to send some message to my android client app. The messages will be injected to the server using a html page( javascript ), which will further be passed on to the android client. I am able to connect these two clients (web and android) individually with the server, however, unable to achieve the flow I want, i.e. Web based javascript sends message to running Nodejs websocket server, which broadcast this message to the android client.
This is the code I am using for server side
var WebSocketServer = require("ws").Server;
var http = require("http");
var express = require("express");
var port = 2001;
var app = express();
app.use(express.static(__dirname + "/../"));
app.get('/someGetRequest', function(req, res, next) {
console.log('receiving get request');
});
app.post('/somePostRequest', function(req, res, next) {
console.log('receiving post request');
});
app.listen(80); //port 80 need to run as root
console.log("app listening on %d ", 80);
var server = http.createServer(app);
server.listen(port);
console.log("http server listening on %d", port);
var userId;
var wss = new WebSocketServer({
server: server
});
wss.on("connection", function(ws) {
console.info("websocket connection open");
var timestamp = new Date().getTime();
userId = timestamp;
ws.send(JSON.stringify({
msgType: "onOpenConnection",
msg: {
connectionId: timestamp
}
}));
ws.on("message", function(data, flags) {
console.log("websocket received a message");
var clientMsg = data;
ws.send(JSON.stringify({
msg: {
connectionId: userId
}
}));
console.log(clientMsg);
});
ws.on("close", function() {
console.log("websocket connection close");
});
});
console.log("websocket server created");
WebClient:
< script type = "text/javascript" >
var websocketURL = 'ws://localhost:2001/';
function startWebSocket() {
try {
ws = new WebSocket(websocketURL);
} catch (e) {
alert("Unable to connect to webserver")
}
}
function sendMessage(text) {
var message = 'Test message from webclient: ' + text;
ws.send(message);
alert(message);
}
startWebSocket(); < /script>
<button onclick="sendMessage('From button1')">Button 1</button > < br >
< button onclick = "sendMessage('From button2')" > Button 2 < /button><br>
Android client:
Just using socket class and its method to do further processing
s = new Socket(HOST, TCP_PORT);
Please let me know how I can pass the message generated from the web client to my android client via websocket server.
I am using nodejs for websocket server implementation.
Thanks
From https://datatracker.ietf.org/doc/html/draft-hixie-thewebsocketprotocol-76
The protocol consists of an initial handshake followed by basic message framing, layered over TCP.
So, just opening a Socket on the client side isn't enough. Maybe this will help https://stackoverflow.com/a/4292671
Also take a look at http:// www.elabs.se/blog/66-using-websockets-in-native-ios-and-android-apps chapter Android client
If you really want to implement the WebSocket stuff yourself, take a look at https://stackoverflow.com/a/8125509 and https://www.rfc-editor.org/rfc/rfc6455
I guess I misread your question. Since the connection between the clients and the server already works, you just need to forward the messages.
First, you need to identify the WebSocket client type (Android or Web). Meaning, you immediately send a message what type of client the newly opened WebSocket connection is and store the WebSocket (ws) for that type in the server. Since you have identified and stored each WebSocket connection, you just forward the message to the other type.
For a more specific answer, I need more information.
Should the communication be bidirectional?
Should there be multiple web and Android connections at the same time?

Node.js simplest code not working

As I am a newbie to Node.js and is learning from different articles. So, far I have learnt, my code is
At server side with app.js
var http = require('http');
var app = http.createServer(function(req,res)
{
req.on('end',function()
{
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello');
});
});
var io = require('socket.io').listen(app);
io.sockets.on('connection',function(socket)
{
socket.emit('connect',{msg:'Hello Client'});
socket.on('client_Says',console.log);
});
app.listen(3000);
At client side with index.html
<script type="text/javascript" src="//localhost:3000/socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect('//localhost:3000');
socket.on('connect',function(data)
{
alert('Server says '+data.msg);
socket.emit('client_Says',{data:'Hello Server'});
});
</script>
What is that I am doing wrong in above code? When I run app.js in console, it says info - socket.io started but when I run http://localhost:3000 it just keep requesting server.
plus I want to know that is it true that wherever on my pc I create my folder for Node and place app.js and index.html files like above in it and run http://localhost:3000 in browser will automatically make that folder my site folder for localhost after running app.js in Node console?
In your app.js update code to this
var http = require('http'),
fs = require('fs'), //<--- File Module
index = fs.readFileSync(__dirname + '/index.html');
var app = http.createServer(function(req,res)
{
res.writeHead(200, {'Content-Type': 'text/html'}); //<-Updated to text/html
res.end(index); //<---I am sending page
});
Hope that solves your problem
You're not supposed to do this on server side:
socket.emit('connect',{msg:'Hello Client'});
because connect is a default event which is emitted on a successful connection from the server. So when a client connects, the server fires its default 'connect' event, but here you're also triggering your event named connect which might be causing problem.

Categories

Resources