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! :)
Related
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.
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');
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.")
I'm completely new to running webservers and their architectures. I'm currently building a web app that has a HTML-based GUI that uses some JavaScript to partially process the user data, then send it as a POST request to the web server.
My question is simple: can the same node.js server be used for serving the HTML webpage as for processing the POST requests, or are two different 'servers' (i.e. two different listeners and ports) needed?
If so, what is the simplest way (I'm happy to use Express.js) My current server file is the following:
var express = require('express'),
serveStatic=require('serve-static'),
mysql = require('mysql');
var app = express();
app.use(serveStatic(__dirname));
var port = 8080;
app.listen(port, function() {
console.log('server listening on port ' + port);
});
app.post('/', function(req, res){
console.log('POST /');
console.dir(req.body);
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('thanks');
});
Just if else block you need with condition request.method == 'POST':
http = require('http');
fs = require('fs');
server = http.createServer( function(req, res) {
console.dir(req.param);
if (req.method == 'POST') { //-- Here Process POST requests
console.log("POST");
var body = '';
req.on('data', function (data) {
body += data;
console.log("Partial body: " + body);
});
req.on('end', function () {
console.log("Body: " + body);
});
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('post received');
}
else
{ //!!!----Here process HTML pages
console.log("GET");
//var html = '<html><body><form method="post" action="http://localhost:3000">Name: <input type="text" name="name" /><input type="submit" value="Submit" /></form></body>';
var html = fs.readFileSync('index.html');
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(html);
}
});
port = 3000;
host = '127.0.0.1';
server.listen(port, host);
console.log('Listening at http://' + host + ':' + port);
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();