简体   繁体   中英

router.get('/page') express Router not working

I am trying to make a simple express routing and I am using vanilla HTML for the front-end.

index.js

const express    = require('express'),
      bodyParser = require('body-parser'),
      serverless = require('serverless-http'),
      app        = express(),
      nav        = require('./routes/nav'), // the router 
      PORT       = process.env.PORT || 8080;

/* Settings */

app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static('./public'));

/* APIS */
app.use('/.netlify/functions/api', nav); //Navigation API

module.exports = app;
module.exports.handler = serverless(app);

if(process.env.NODE_ENV === "development"){
  app.listen(PORT, () => {
    console.log(`Server is runing on PORT: ${PORT} ENV: ${process.env.NODE_ENV}`);
  });
}

nav.js

const express    = require('express');

const router     = express.Router();
const PATH       = "../../public/";

router.get('/', (req, res) => {
  res.render(`${PATH}index.html`)
});

router.get('/graph', (req, res) => {
  res.render(`${PATH}pages/graph.html`)
})


module.exports = router;

every time I try to route using the tag it tells me "Can not get /graph"

my HTML nav

<ul class="navbar-nav mr-auto">
          <li class="nav-item"><a class="nav-link" href="/">Home</a></li>
          <li class="nav-item mr-auto"><a class="nav-link" href="/graph">Graph Algorithims</a></li>
          <li class="nav-item"><a class="nav-link" href="/sort">Sorting Algorithims</a></li>
</ul>
      

I thought the problem might be on the local server and I tried deploying to netlify to see if it works there and the same problem occurs.

Reading your code, I can't seem to see where you "connect" the router.js file into your index.js.

To fix this, add the following in index.js:

const router = require('path/to/router.js');
app.use(router);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM