简体   繁体   中英

Cannot Get Index.ejs Using Express.js

I'm taking a Linkedin course on building a website using express.js I'm trying to get my index.ejs page to render, however the server keeps rendering my index.html page.

I've already checked other overflow articles but it just shows to switch params (req,res), put ("index"), and to combine the app.get statement.

Here is my server.js code

const { response } = require('express');
const express = require('express');
const path = require('path');

const app = express();
const port = 3000;

app.set('view engine', 'ejs');

app.set('views', path.join(__dirname, './views'));

app.use(express.static(path.join(__dirname, './static')));

app.get('/', (req, res) => {
  response.render('index', { pageTitle: 'Welcome' });
  });

app.get('/speakers', (req, res) => {
  response.sendFile(path.join(__dirname, './static/speakers.html'));
});

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
});

If I remove my index.html file I get this error message

TypeError: Cannot read properties of undefined (reading 'app')
    at ServerResponse.render (D:\building-website-nodejs-express\node_modules\express\lib\response.js:1017:22)
    at D:\building-website-nodejs-express\server.js:24:12
    at Layer.handle [as handle_request] (D:\building-website-nodejs-express\node_modules\express\lib\router\layer.js:95:5)
    at next (D:\building-website-nodejs-express\node_modules\express\lib\router\route.js:144:13)
    at Route.dispatch (D:\building-website-nodejs-express\node_modules\express\lib\router\route.js:114:3)
    at Layer.handle [as handle_request] (D:\building-website-nodejs-express\node_modules\express\lib\router\layer.js:95:5)
    at D:\building-website-nodejs-express\node_modules\express\lib\router\index.js:284:15
    at Function.process_params (D:\building-website-nodejs-express\node_modules\express\lib\router\index.js:346:12)
    at next (D:\building-website-nodejs-express\node_modules\express\lib\router\index.js:280:10)
    at SendStream.error (D:\building-website-nodejs-express\node_modules\serve-static\index.js:121:7)

Here is my folder structure Picture Of VS Code Folders and Server.js

Please make sure your filepath is correct, normally it should like this.

    app.set('views', path.join(__dirname, 'views'));

    app.use(express.static(path.join(__dirname, 'static')));

Please make sure your index.ejs is in the views folder. Change the "response" to "res" since your parameter in function it "res".

    app.get('/', (req, res) => {
      res.render('index', { pageTitle: 'Welcome' });
    });

This applies for all the times you used response. change it to res.

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