Node.js访问localhost:5001出现Cannot GET /错误求助
Node.js访问localhost:5001出现Cannot GET /错误求助
兄弟,我仔细瞅了你的代码和问题描述,一眼就发现问题出在哪儿啦!
先看你贴的index.js代码,这里有个低级拼写错误:
const path = require("path"); const express = require("express"); const exp = require("constants"); const dotenv = require("dotenv").config(); const port = process.env.PORT || 5001; const app = express(); //enable body parser app.use(express.json()); app.use(express.urlencoded({ extended: false })); //set static folder app.use(express.static(path.join(__dirname, 'pubic'))); // 这里的文件夹名拼写错啦! app.use('/openai', require("./routes/openaiRoutes")); app.listen(port, () => console.log(`Server started on port ${port}`));
你把静态文件夹的名字写成了pubic,但实际你的文件夹是public,这就导致Express找不到对应的静态资源目录,访问根路径/时自然返回Cannot GET /错误了。
解决办法超简单:
- 把代码里的
'pubic'改成'public',修正后的代码行如下:app.use(express.static(path.join(__dirname, 'public'))); - 重启你的Node.js服务器,再访问
localhost:5001,应该就能正常加载public文件夹里的index.html啦!
另外再确认下,public文件夹确实和index.js在同一个目录下哦,这样__dirname拼接出来的路径才是正确的。
备注:内容来源于stack exchange,提问作者bizimunda
相关产品推荐
相关产品推荐

