I just want to know how can we achieve wild card routing in pure http.createServer without using express.
in express we would do something like below
var express = require('express');
var http = require('http');
var app = express();
app.get('/',function(req,red)
{
res.send("I am foo");
});
app.get('/:id',function(req,res)
{
res.send("I am Foo with id " + red.params.id);
});
but I wasn't able to find the equivalent in http.createServer
var http = require('http');
//create a server object:
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
var url = req.url;
if(url ==='/'){
res.write('i am foo');
res.end();
}else if(url ==='/:id'){//
res.write('I am foo with id');
res.end();
}
}).listen(3000, function(){
console.log("server start at port 3000");
});
one way we could achieve this is using pattern matching but I don't think its a feasible solution.
Related
im writing a webserver in nodeJs as seen in the following code. I got the server working but sadly i cant acces the website outside my network (localhost). How can i do this?
var connect = require('connect');
var serveStatic = require('serve-static');
connect().use(serveStatic(__dirname)).listen(80, function(){
console.log('Server running on 80...');
});
I also used this method to check if the other method was the problem.
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res){
fs.readFile('Index.html', function (err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
})
}).listen(80);
Have you tried binding the port externally ?
connect().use(serveStatic(__dirname)).listen({
host: '0.0.0.0',
port: 80
}, function(){
console.log('Server running on 80...');
});
i am quiet new to express . I have searched a lot and unable to find the answer.
i am receiving headers in my express app, but when i try to set those headers to be accessible by angular, it returns undefined. how ever hard coded header appears perfectly at angular end in networks tab of chrome. Here is the code
express code
var express = require('express');
var config = require('./config')[process.env.NODE_ENV || 'dev'];
var app = express();
app.get('/*', function (req, res) {
res.sendFile(__dirname + '/public/index.html');
var token=req.header('x-access-token');
//var token='123'
console.log(token);
res.set('x-access-token',token);
});
var server = app.listen(process.env.PORT || 3000, function() {
console.log('server started. Listening on port '+3000);
});
Angular code
$http.get($scope.windowURL
).
success(function(data, status, headers, config) {
$scope.token=headers('x-access-token')
console.log($scope.token);
alert($scope.token)
})
.error(function(data, status, headers, config) {
alert('notoken')
});
and i am getting 'undefined' in headers if set dynamically by express app.
You should set the header, before finishing the response with res.sendFile();
var express = require('express');
var config = require('./config')[process.env.NODE_ENV || 'dev'];
var app = express();
app.get('/*', function (req, res) {
var token=req.header('x-access-token');
//var token='123'
console.log(token);
res.set('x-access-token',token);
res.sendFile(__dirname + '/public/index.html');
});
var server = app.listen(process.env.PORT || 3000, function() {
console.log('server started. Listening on port '+3000);
});
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();
actally i'm trying to serve a html file in the browser using node js and express. unfortunatly i can't get the correct appearence of the html file.
here is the code :
var http = require('http');
var fs = require('fs');
// Chargement du fichier index.html affiché au client
var server = http.createServer(function(req, res) {
fs.readFile('./table.html', 'utf-8', function(error, content) {
res.writeHead(200, {"Content-Type": "text/html"});
res.end(content);
});
});
To send a single file for a specific route use the res.sendFile() function.
var express = require('express');
var app = express();
var path = require('path');
app.get('/', function(req, res) {
res.sendFile(path.resolve('path/to/my/file.html'));
});
app.listen(3000);
In case you want to serve all files in a directory use the express.static() middleware
var express = require('express');
var app = express();
app.use(express.static('path/to/my/directory'));
app.listen(3000);
With express u can do something like
//init the app to extend express
var express=require("express");
var app=express();
//inside the http callback
var server = http.createServer(function(req, res) {
app.use(express.static("./file"));
})
server.listen(8000);