javascript - router.get 不起作用,但带有 id 的 router.get 有效
问题描述
调用http://localhost:5000/surveycreate/4可以工作并将我重定向到surveypage.html
但是调用http://localhost:5000/surveycreate不起作用,它会将我的主要 index.js 文件重定向到公共文件夹中它甚至不打印“常规获取”
为什么会这样?
路线中的surveypage.js
const path = require("path");
const router = express.Router();
router.use(express.static(path.join(__dirname, "../public")));
router.get('/:id', async (req, res) => {
console.log("get with id");
res.sendFile(path.join(__dirname, "../public/Surveypage.html"));
})
router.get('/', async (req, res) => {
console.log("regular get");
res.sendFile(path.join(__dirname, "../public/Surveypage.html"));
})
module.exports = router; ```
==============================================================================
index.js of node:
const surveyPage = require('./routes/surveypage')
const app = express();
app.use(express.json());
app.use('/surveypage',surveyPage)
app.use(express.static(path.join(__dirname, "/public")));
app.use(cors())
const PORT = process.env.PORT || 5000
app.listen(PORT , () => {
console.log(`Listenning on porst ${PORT }`);
})
解决方案
确保您的文件结构与您的代码相对应。
以下代码对我来说效果很好:
应用程序.js:
const express = require("express");
const app = express();
const cors = require("cors")
const surveyPage = require('./routes/surveypage')
const path = require("path");
const PORT = process.env.PORT || 5000
app.use(express.json());
app.use('/surveypage', surveyPage)
//app.use(express.static(path.join(__dirname, "/public"))); // not needed
app.use(cors())
app.listen(PORT, () => console.log(`Listenning on porst ${PORT }`))
调查页面.js
const path = require("path");
const express = require('express')
const router = express.Router();
router.use(express.static(path.join(__dirname, "../public")));
router.get('/:id', (req, res) => res.sendFile(path.join(__dirname, "../public/Surveypage.html")));
router.get('/', (req, res) => res.sendFile(path.join(__dirname, "../public/Surveypage.html")))
module.exports = router;
推荐阅读
- lazarus - Free Pascal / Lazarus:为什么在我的示例中没有调用“FormCloseQuery”事件?
- opendaylight - 如何在 Opendaylight 中操作 YANG 生成的 REST API GET?
- c++ - 编译Qt项目,报错QQmlEngine: No such file or directory 编译终止
- twilio - Twilio - 如何在我的应用程序中获取请求检查员?
- javascript - Angular - Map/Catch 返回相同的值但收到错误
- javascript - setInterval 会阻止/干扰 node.js/express HTTP 服务器吗?
- python - 仅转置数据框中的几列和几行
- google-chrome-extension - 使用 Web 扩展清除 HTTP Basic Auth
- python - 通过在 pandas 中保留小时数进行分组
- c - 如果有两个空格,则将其计为 3 个单词