【问题标题】:router.get doesn't work but router.get with id worksrouter.get 不起作用,但带有 id 的 router.get 有效
【发布时间】:2019-11-06 01:03:44
【问题描述】:

调用http://localhost:5000/surveycreate/4 有效并将我重定向到 调查页.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 }`);

})

【问题讨论】:

    标签: javascript express web-applications routes


    【解决方案1】:

    确保您的文件结构与您的代码一致。

    以下代码对我来说效果很好:

    app.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 }`))
    

    surveypage.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;
    

    【讨论】:

      猜你喜欢
      • 2015-04-29
      • 2019-09-03
      • 2017-04-18
      • 2019-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多