I'm trying to use the code below but it doesn't work for me because the server doesn't connect and there's no error in the console.
var PORT=8080;
var http=require('http');
var http=require('swig');
var http=require('url');
exports.startServer=function (PORT){
var server=http.createServer(function(req,res){
var page=url.parse(req.url).pathname;
if(page=='/'){
res.writeHead(200,{'Content-Type':'text/html'});
res.write(swig.renderFile('templates/home.tpl',{
name :'user'
})
);
} else{
res.writeHead(404,{'Content-Type':'text/html'});
res.writeHead('<h1>Error 404 : page not found</h1>');
}
res.end();
});
server.listen(PORT);
console.log('Server running on'+ PORT);
}
The reason I think is that you have assigned the variable http
for three times, which makes that only the last one takes effect.
Try to replace
var http=require('http');
var http=require('swig');
var http=require('url');
with
var http=require('http');
var swig=require('swig');
var url=require('url');
check any other server running on same port or not
if it is running, change port number
var port = process.env.PORT | 3000;
change this
var http=require('http');
var swig=require('swig');
var url=require('url');
Better to use express.
var express = require('express');
var app = express();
var port = process.env.PORT | 3000;
var server = app.listen(port,'0.0.0.0',function(){
var host = server.address().address;
var port = server.address().port;
console.log("Server listen to : "+host+":"+port);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.