NodeJS 无法获取要在HTML中呈现的EJS文件:出了什么问题?

smdnsysy  于 2023-06-05  发布在  Node.js
关注(0)|答案(1)|浏览(153)

我无法将我的EJS文件呈现为HTML。每次我试图访问我的EJS文件,我得到一个“无法获取/store. html”的响应。

if (process.env.NODE_ENV !== 'production') {
    require('dotenv').config()
}

const stripeSecretKey = process.env.STRIPE_SECRET_KEY
const stripePublicKey = process.env.STRIPE_PUBLIC_KEY

const express = require('express')
const path = require('path')
const app = express()
const fs = require('fs')
const stripe = require('stripe')(stripeSecretKey)

app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')
app.use(express.json())
app.use(express.static('public'))

app.get('/store', (req, res) => {
fs.readFile('items.json', (error, data) => {
    if (error) {
        res.status(500).end()
    } else {
        res.render('store.ejs', {
            items: JSON.parse(data)
        })
    }
})
})

app.listen(3000)

我想知道我该怎么做?

v440hwme

v440hwme1#

在继续之前,请检查您的路由,/store.html错误,您应该像这样调用此API http://localhost:3000/store
如果它不工作如下:
检查你是否已经安装了ejs包。您正在尝试访问扩展名为.htmlejs文件,这不正确。您应该使用与文件名相同的扩展名,例如views文件夹中的/store.ejs
/store.html更改为/store.ejs
我希望这个解决方案对你有帮助。

相关问题