简体   繁体   中英

Node/Express cannot GET any of my html/js/css files

I have a Node/Express application. There is a client side app as well, with multiple html files and multiple js files. I am using WebStorm, and clicking on RUN. This prints out in the console:

"C:\Program Files (x86)\JetBrains\WebStorm 2016.2.2\bin\runnerw.exe" "C:\Program Files\nodejs\node.exe" "C:\Users\name\Downloads\Fall 2016\Web\thing\src\server\index.js"
Shuffle router is loaded
I am open
Example app listening on 8080

So the express part works.

However, when I go to " http://localhost:8080/game.html " I get Cannot GET /game.html . This happens for all css pages as well. I can open the html pages using the preview(?) button in Webstorm, but that opens " http://localhost:63342/ ".

My folder structure is this:

public 
  css
     style.css
  img
     card1.jpg
  js
     game.js
  game.html
src
  server
     routes
       shuffleRoutes.js
     index.js

My index.js starts with this snippet of code before defining some functions:

let express         = require('express'),
    bodyParser      = require('body-parser'),
    logger          = require('morgan'),
    _               = require('lodash');
let path = require('path');

    //redis, session
let app = express();
app.use(logger('combined'));
app.use(express.static('public'));
app.use(bodyParser.json({}));
app.use(bodyParser.urlencoded({ extended: true }));

app.use('/img',express.static(path.join(__dirname, 'public/img')));
app.use('/js',express.static(path.join(__dirname, 'public/js')));
app.use('/css',express.static(path.join(__dirname, 'public/css')));

app.get("/v1/game", require("./routes/shuffleRoute.js"));

console.log("I am open");

and has this at the end of the file

  let server = app.listen(8080, function () {
    console.log('Example app listening on ' + server.address().port);
});

My game.js doesn't have any reference to the index.js file. My game.html file only has <script src="./js/game.js"></script> .

How do I fix the error of not getting anything when I run the Webstorm project and go to localhost:8080/game.html?

You need to define an endpoint for the express to use,

So you need to serve the game.html to that route:

Since you are rendering html you will need to use ejs.

So adding

 //configuration  
    app.engine('html', require('ejs').renderFile);
    app.set('view engine', 'ejs');

//route
    app.get('/game',function(req,res,next){
     res.render('game.html');
    });

Now go to localhost:8080/game

This should show your game.html

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM