简体   繁体   中英

Can I change my .ejs file to .html to make it work with Node.js and Express?

I have a index.html and wanted to link it to a twitter.ejs page. I was unsuccessful and now I am wondering if I can just change the extension from ejs to html. I tried to do it, but it does not work. Does only Node.js/Express work with a .ejs file?

My code trying to redirect from index.html to twitter.ejs: http://jsfiddle.net/1moj4v07/4/

index.html

<li><a href="/twitter">Tweet!</a></li>

script.js

const express = require('express');
const bodyParser= require('body-parser')
const app = express();
const MongoClient = require('mongodb').MongoClient
var router = express.Router();

var db

MongoClient.connect('mongodb://name:password@cluster0-shard-00-00-fquoc.mongodb.net:27017,cluster0-shard-00-01-fquoc.mongodb.net:27017,cluster0-shard-00-02-fquoc.mongodb.net:27017/twitter?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin', (err, database) => {
  if (err) return console.log(err)
  db = database
  app.listen(3000, () => {
    console.log('listening on 3000')
  })
})

app.use(bodyParser.urlencoded({extended: true}))

var path = require('path')


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

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

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

app.get('/', (req, res) => {
  db.collection('tweets').find().toArray((err, result) => {
    if (err) return console.log(err)
    res.render('twitter.ejs', {tweets: result})
  })
})

app.get('views/', (req, res) =>{
  res.render(views,local)
})

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

app.post('/tweets', (req, res) => {
  db.collection('tweets').save(req.body, (err, result) => {
    if (err) return console.log(err)
    console.log('saved to database')
    res.redirect('/')
  })
})

Folder structure

 twitter
    ├── views
    |   └── twitter.ejs
    |   
    ├── public
    |   └── styles.css
    |
    ├── index.html  

I have a index.html and wanted to link it to a twitter.ejs page. I was unsuccessful and now I am wondering if I can just change the extension from ejs to html. I tried to do it, but it does not work. Does only Node.js/Express work with a .ejs file?

Express does indeed support formats other than .ejs , such as .html like you've asked, you'll just need to setup a new View Engine to support this. However, it looks like you have a number of other issues related to the structure of your Node application and the way your routes are loading its views.

To get a .html file rendered via Express, you can use res.render() with HTML files by creating a new View Engine in Express and then using that. The only requirement is that ejs is installed via npm i --save ejs . We need the ejs package directly because you'll need the renderFile() function for our new html view engine. Once you make the below change you can use res.render() to render a .html file.

This approach will not break data injection using EJS since renderFile() is still being used. The whole point of this approach is to continue getting EJS functionality if needed but, it will also render standard HTML as well all with one View Engine.

You also have a number of things that don't make sense in the given code along with a bad structure of your views.

  • index.html isn't being served
  • twitter.ejs is returned at the root of the app
  • app.get('views/') uses a views variable that is never defined

I've given a new Express Server setup and Project Directory Structure


Folder Structure for App

/public
  /styles
    styles.css
/views
  index.html
  twitter.html
server.js
package.json  

Updated Express Server

const express = require('express')
const bodyParser = require('body-parser')
const MongoClient = require('monogdb').MongoClient
const path = require('path')

const app = express()
let db

MongoClient.connect('<connectionString>', (err, database) => {
  if (err) {
    return console.log(err)
  }

  db = database
  app.listen(3000, () => console.log('listening on 3000'))
})

app.engine('html', require('ejs').renderFile)
app.set('view engine', 'html')
app.set('views', path.join(__dirname, 'views'))
app.use(bodyParser.urlencoded({extended: true})
app.use(express.static(path.join(__dirname, 'public')))

// When at the base of the application, return /views/index.html
app.get('/', (req, res) => {
  return res.render('index')
})

// When GET /twitter is requested, get tweets from DB 
// and render /views/twitter.html
app.get('/twitter', (req, res) => {
  db.collection('tweets').find().toArray((err, tweets) => {
    if (err) {
      console.log(err)
      return res.sendStatus(500)
    }

    return res.render('twitter', {tweets})
  })   
})

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