“Cannot GET /” with Connect on Node.js

后端 未结 10 1228
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-01 00:40

I\'m trying to start serving some static web pages using connect like this:

var connect = require(\"connect\");
var nowjs = require(\"now\");
va         


        
相关标签:
10条回答
  • 2020-12-01 01:22

    Had the same issue. It was resolved as described above.

    In my index.js

    var port = 1338,
    express = require('express'),
    app = express().use(express.static(__dirname + '/')),
    http = require('http').Server(app),
    io = require('socket.io')(http);
    
    app.get('/', function(req, res){
        res.sendFile(__dirname + '/index.html');
    });
    
    io.on('connection', function(socket){
        console.log('a user connected');
    });
    
    http.listen(port, function(){
        console.log("Node server listening on port " + port);
    });
    

    and in my index.html

    <!doctype html>
    <html>
        <head>
            <title>
                My page
            </title>
        </head>
        <body>
            <script src = "lib/socket.io.js"></script>
            <script src = "lib/three.js"></script>
            <script>
                var socket = io();
            </script>
        </body>
    </html>
    

    the three.js was just in there for path testing. This will set all child files to start at the root directory of your app. Also socket.io.js can be called automatically using <script src = "/socket.io/socket.io.js"> through some dark magic (since there is physically a node_modules and lib directory in between) .

    0 讨论(0)
  • 2020-12-01 01:22

    You typically want to render templates like this:

    app.get('/', function(req, res){
      res.render('index.ejs');
    });
    

    However you can also deliver static content - to do so use:

    app.use(express.static(__dirname + '/public'));
    

    Now everything in the /public directory of your project will be delivered as static content at the root of your site e.g. if you place default.htm in the public folder if will be available by visiting /default.htm

    Take a look through the express API and Connect Static middleware docs for more info.

    0 讨论(0)
  • 2020-12-01 01:27

    You might be needed to restart the process if app.get not working. Press ctl+c and then restart node app.

    0 讨论(0)
  • 2020-12-01 01:29

    The solution to "Cannot Get /" can usually be determined if you do an "ng build" in the command line. You will find most often that one of your "imports" does not have the correct path.

    0 讨论(0)
提交回复
热议问题