Node.js中出现Cannot GET /store.html错误,求解决方法
Hey there, let's break down why you're hitting that Cannot GET /store.html error and how to fix it quickly:
The Root Cause
Looking at your code, you've defined a route for /store (not /store.html) that renders the store.ejs template. When you try to access /store.html, Express doesn't have any route configured to handle that path—hence the error.
Solutions to Try
1. Access the Correct Path
The simplest fix is to visit http://your-server-url/store instead of /store.html. Your existing /store route will handle this request, read your items.json file, and render the EJS template properly.
2. Add a Route for /store.html
If you need to support the /store.html path (for compatibility or user habits), you have two options:
Option A: Redirect to /store
Add this route to your code to automatically send users to the correct path:
app.get("/store.html", (req, res) => { res.redirect("/store"); });
Option B: Directly Render the Template for /store.html
Duplicate (or refactor) your existing route logic to handle /store.html:
app.get("/store.html", function(req, res) { fs.readFile('items.json', function(error, data) { if (error) { res.status(500).end() } else { res.render('store.ejs', { stripePublicKey: stripePublicKey, items: JSON.parse(data) }) } }) })
3. Double-Check Your Static Files & Template Setup
- Make sure your
store.ejsfile is located in aviewsfolder (Express looks here by default when using EJS as the view engine). - Confirm that
items.jsonis in the root directory of your project (or adjust the file path infs.readFileif it's elsewhere). - Since you're using
app.use(express.static('public')), any files in thepublicfolder are served as static assets—but yourstorepage is a dynamic EJS template, so it won't be served from here unless you specifically add a static HTML file there.
内容的提问来源于stack exchange,提问作者lebaneseblonde252

