Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node/express anchor link route

I am making a website and for the frontend, I am using HTML. For the backend, I am using node/Express.

In HTML, I have some anchor tag that redirects different HTML page. To create different routes I used Router in Express.

Now the problem is when I run my website through node then the redirection is not working as expected.

index.html:

        <li><a href="index.html">Home</a></li>
        <li><a href="publication.html">Publication</a></li>
        <li><a href="team.htm">Team</a></li>
        <li><a href="contact.html">Contact</a></li>

ExpressJS:

index.js:

  var express = require('express');
  var path = require('path');
  //router object
 var router = express.Router();

 router.get('/', function (req, res) {
  res.sendFile(path.join(__dirname, '..', '/public/html/index.html'));
 });

  module.exports = router;

publication.js:

   var express = require('express');
   var path = require('path');

  //router object
  var router = express.Router();

  router.get('/publication', function(req, res){
    res.sendFile(path.join(__dirname, '..', '/public/html/publication.html'));
  });

  module.exports = router;

When I run the website through node and type:

localhost:3000/publication

then I am getting the publication.html and when I type

localhost:3000

it opens the index.html and in my index page, I have above anchor tags. Now if I click any of my anchor tags then I am getting an error message like "cannot get publication.html" what I want is to redirect to my publication.js and calls the

router.get('/publication')

method and then open the publication.html

Can anyone point me to the right direction?

like image 783
jackysatpal Avatar asked Aug 13 '17 15:08

jackysatpal


1 Answers

This code

    <li><a href="index.html">Home</a></li>
    <li><a href="publication.html">Publication</a></li>
    <li><a href="team.htm">Team</a></li>
    <li><a href="contact.html">Contact</a></li>

will generate the links like http://localhost:3000/index.html. Now you backend does not know this route because you defined your routes like /publication and so on. You have to modify it to something like below

    <li><a href="/">Home</a></li>
    <li><a href="publication">Publication</a></li>
    <li><a href="team">Team</a></li>
    <li><a href="contact">Contact</a></li>

More on express routing

like image 191
Arpit Solanki Avatar answered Oct 05 '22 18:10

Arpit Solanki