Sending object from node server to javascript on client side - javascript

I have a very simple server like this:
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/html' });
fs.readFile('index.html', 'utf-8', function (err, content) {
if (err) {
res.end('something went wrong.');
return;
}
res.end(content);
});
}).listen(8080);
console.log("Server running on port 8080.")
This takes care of rendering my html, but now I want to send an object. Something like this:
var arr = [1,2,3];
I want to be able to manipulate this object on the client side using js. So in addition to knowing how to send it from server to client, I would like to know how to receive it in the client, if that makes sense.
I am trying to learn how things happen behind the scene so I do not want to use express.

The only thing you can exchange via HTTP protocol in general is data. Not objects, not html files, just data.
The process of converting objects to data and back is called serialization.
For your specific case of simple objects, you can use JSON built-in object to serialize your objects.
At server:
var data = JSON.stringify(arr);
res.end(data);
At client:
var arr = JSON.parse(data);
As to how to ask and receive data on client, try googling XmlHTTPRequest.
On request, adding fully functional server-side code:
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': '*' });
var data = JSON.stringify([1, 2, 3]);
res.end(data);
}).listen(8080);
console.log("Server running on port 8080.")
the Access-Control-Allow-Origin header was only necessary to be able to run your code in console (it is called 'CORS' and means this endpoint can be requested from pages hosted on other domains)

Simply change the response type and stringify the JSON:
http.createServer(function (req, res) {
var arr = [1,2,3];
res.writeHead(200, { 'Content-Type': 'application/json'});
res.end(JSON.stringify(content), 'utf-8');
}).listen(8080);

Ok so seems like I was doing a few things wrong. It mainly had to do with the routing on the server. This is what I had tried to do:
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
var arr = [1, 2, 3];
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(arr), 'utf-8');
}).listen(8080);
console.log("Server running on port 8080.")
And on client side I had something like this:
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://localhost:8080/", true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
console.log(JSON.parse(xmlhttp.responseText));
}
}
xmlhttp.send();
For some reason, the console.log would never happen and I would just get the array printed on the page. But by adding some routes to my server like this, it worked:
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
if (req.method === 'GET' && req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/html' });
fs.readFile('index.html', 'utf-8', function (err, content) {
if (err) {
res.end('something went wrong.');
return;
}
res.end(content);
});
}
if (req.method === 'GET' && req.url === '/data') {
var arr = [1, 2, 3];
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(arr), 'utf-8');
}
}).listen(8080);
console.log("Server running on port 8080.")

Related

Trouble getting my node.js server to listen with

I am learning node.js and I am trying to figure out how I can get my program to listen at a specific port, but I just keep getting error messages. Is there any easier way I could be doing this, or what do I need to change in my code to allow this to work?
const http = require('http');
const port = 3000
const requestHandler = (request, response) => {
console.log(request.url)
response.end('server is listening!')
}
const server = http.creatServer(requestHandler)
server.listen(port, (err) => ) {
console.log('server is listening on ${port}')
}
I think you should try something like the following to get started.
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('Hello World!');
res.end();
}).listen(8080);
Or in your case, I think that the following changes will work:
const http = require('http');
const port = 3000
const requestHandler = (request, response) => {
console.log(request.url)
response.end('server is listening!')
}
const server = http.createServer(requestHandler)
server.listen(port, (err) => {
console.log('server is listening on ${port}')
})
It seems you had a syntax error as well as a typo in your code.

How can i handle SYN / RST packets on nodejs server?

I'm trying to build a simple server for a cyber research on the university. All I need is handling some requests which the server gets.
I've succeeded with GET methods, and I have to handle some more packets over Transport layer - SYN and RST.
Example: When a SYN packet arrives, the server has to send back SYN-ACK packet.
I started creating my server with http module, but I'm not sure that it could handle TCP packets, and I can't find any source for handling TCP packets.
Here is what I've started coding:
'use strict'
let http = require('http');
let fs = require('fs');
let path = require('path');
let PORT = 4500;
let address = "127.0.0.1";
require('dns').lookup(require('os').hostname(), function (err, add, fam) {
address = add;
});
let server = http.createServer(function (req, res) {
console.log(`${req.method} request for ${req.url}`);
if (req.url === '/') {
fs.readFile('./index.html', function(err,data) {
if (err) {
throw err;
}
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(data);
});
} else if (req.url.match(/.jpg$/)) {
let imgPath = path.join(__dirname, 'images', req.url);
let imgStream = fs.createReadStream(imgPath);
res.writeHead(200, {'Content-Type': 'image/jpeg'});
imgStream.pipe(res);
} else {
res.writeHead(404, {"Content-Type": "text/plain"});
res.end("404 File Not Found");
}
});
server.listen(PORT, address);
console.log(`Server is running on ip ${address}, port ${PORT}.`);
I'm really new to JavaScript and Node.js, so any code suggestions will be welcomed! :)

How to listen to GET requests using only http with node? No express

I'm wondering how to listen to http get requests with only "require http" instead o f express.
This is what I have now:
let http = require('http');
let server = http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello, World!\n');
});
server.listen(8443);
console.log('Server running on port 8443');
I want to listen to get requests, and console.log the url. and if there is any other request i want to print ("bad request").
You need to check what method was used using http: message.method and if it is not GET then send another response.
'use strict'
let http = require('http');
let server = http.createServer(function (req, res) {
if( req.method === 'GET' ) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello, World!\n');
} else {
res.writeHead(405, {'Content-Type': 'text/plain'});
res.end('Method Not Allowed\n');
}
});
server.listen(8443);
console.log('Server running on port 8443');

Loading JSON files during Express app initialization

I have a movie-finding app that makes API calls in the backend. During initialization I need to load some JSON files: one (lang.json) contains a list of languages for searching purposes, the other (stored in the config variable) is used to get a link to the movie poster.
How would I ensure the loading of these files is completed before an HTTP request is made? One solution I can think of involves putting the calls to app.get() and app.listen() inside fs.readfile()'s callback. But is there a better way? Web development is totally new to me.
var express = require('express');
var app = express();
var fs = require('fs');
var request = require('request');
var merge = require('merge');
require('dotenv').config();
var apiKey = process.env.API_KEY;
var config = {};
app.use(express.static('view'));
// TODO load config and lang before below code
app.get('/lang', function(req, res) {
fs.readFile('lang.json', function(err, data) {
if (err) throw err;
res.json(JSON.parse(data));
});
});
app.get('/genres', function(req, res) {
request.get({
url: 'http://api.themoviedb.org/3/genre/movie/list',
qs: {api_key: apiKey}
}, function(error, response, body) {
res.json(JSON.parse(body).genres);
});
});
app.get('/randomMovie', function(req, res) {
request.get({
url: 'https://api.themoviedb.org/3/discover/movie',
qs: merge(req.query, {api_key: apiKey})
}, function(error, response, body) {
body = JSON.parse(body).results;
var len = body.length;
var i = Math.floor(Math.random() * len);
var movie = body[i];
// movie.poster_path = movie.images.base_url + movie.images.poster_sizes[6] + movie.poster_path;
res.json(movie);
});
});
app.listen(3000, function() {
console.log('server started on port 3000');
});
The easiest way is to just use fs.readFileSync() before your call to app.listen(). For example:
var lang = fs.readFileSync('lang.json');
app.get('/lang', function(req, res) {
res.setHeader('Content-Type', 'application/json');
res.send(lang);
});
// ...
Just be aware that the contents of lang will not automatically update if the contents of lang.json change on disk during the lifetime of your node process.

Display output from Python in Node.js server

I want to display all the output from pokecli.py on a web page that can be accessed from http://192.168.32.100:8081. Currently I am getting a "connection refused" from Chrome, but no errors when running node myscript.js.
I am new to Node and I am not exactly sure if this is right. I want to display the output in real time. I know this is possible even without NGINX since I can get output from the following example code by opening http://192.168.32.100:8080:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(8080, '192.168.0.251');
console.log('Server running at http://192.168.0.251:8080/');
Here is my code:
var http = require('http');
var PythonShell = require('python-shell');
var express = require('express');
var app = express();
// Options to be used by request
var options = {
host: '127.0.0.1',
port: '8081'
};
// Callback function is used to deal with response
var callback = function(response){
// Continuously update stream with data
var body = '';
response.on('data', function(data) {
body += data;
PythonShell.run('pokecli.py', function (err) {
if (err) throw err;
console.log('finished');
});
});
response.on('end', function() {
// Data received completely.
console.log(body);
});
}
// Make a request to the server
var req = http.request(options, callback);
app.get('/', function (req, res) {
res.send('Hello World!'); // This will serve your request to '/'.
});
app.listen(8081, function () {
console.log('Example app listening on port 8081!');
});
req.end();

Categories

Resources