基本的app+express+mongodb+如何不使用端口



这是我的一个基本应用程序,它使用express设置路线,还可以查询mongo db

如果我转到http://localhost:8080/,浏览器中将显示views/hello.html中的任何内容。如果我转到http://localhost:8080/test,浏览器中将显示"这是一个测试页面"。

我的问题是,为什么我必须在地址中指定端口8080?或者换句话说,如何在不指定端口的情况下在地址http://localhost/显示我想要的内容?

我知道我可以通过更改此处的8080值来更改端口

app.listen(8080);

下面的基本应用程序:

var express = require('express'),
    app = express(),
    cons = require('consolidate'),
    crypto = require('crypto'),
    MongoClient = require('mongodb').MongoClient;
app.engine('html', cons.swig);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');
MongoClient.connect('mongodb://localhost:27017/m101', function(err, db) {
    if(err) throw err;
    //set up a route to go to the page http://localhost:8080/ to see 'This is a test Page' 
    app.get('/', function(req, res){

        db.collection('hw1_3').findOne(function(err, doc) {
             //do stuff here 
             return res.render('hello', { "name" : decrypted });
        });
    });
    //set up a route to go to the page http://localhost/test to see 'This is a test Page' 
    app.get('/test', function(req, res){
        return res.send('This is a test Page!!', 200);
    });
    app.listen(8080);
    console.log('Express server started on port 8080');
});

http流量的默认端口是80。如果绑定到80以外的任何端口,则需要在URL中指定端口。app.listen(80)会处理你的问题。

在Unixy系统上,绑定到任何小于1024的端口都需要root(管理员)访问权限,因此您必须像sudo node server.js一样运行服务器才能获得端口80。在这种情况下,您应该在机器上进行开发时绑定到更高的端口(如8080)。

我很傻,但我想说localhost:8080代替了www.somesite.com。我不会太在意端口号。如果你把它部署到heroku或其他什么地方,你就看不到它了。

最新更新