Home > Mobile >  Express routing in Node JS returns 404 on live server, but not test system
Express routing in Node JS returns 404 on live server, but not test system

Time:01-07

So I'm fairly new to NodeJS, and I wanted to try routing with it, however I've come across a weird issue, I'm not sure if it's my hosting provider having some weird config issue on their end.

But here's my scenario, I have a site with a fair amount of pages which are generated from a database based on locations saved in the database, so for example, if there are three cities saved in the database, I would need:

mydomain.com/BigCity

mydomain.com/OtherBigCity

mydomain.com/SmallCity

Again, these cannot be hard coded.

So here is my basic code for just testing the redirects:

'use strict';
var path = require('path');
var express = require('express');
var fs = require('fs');
var app = express();

// Different variations of things I have tried (including hard coding just for testing)
app.use('*', render);
app.use('/*/', render);
app.use('/*', render);
app.use('/', render);
app.use('Location2', render);
app.use('/Location1', render);

var server = app.listen(process.env.PORT || 3000, function (r) {
    console.log('listening');
});

function render(req, res) {
    fs.readFile(path.resolve("./index.html"), "utf-8", (err, data) => {
        if (err) {
            console.log(err);
            return res.status(500).send("An error occured");
        }

        return res.send(
            data.replace(
                '<div id="root"></div>',
                `<h1>Test</h1><b>${req.originalUrl}</b><br/><b>${req.url}</b>`
            )
        )
    })
}

So on my local system, it works perfectly fine, and outputs as expected, but when I deploy to my hosting, only the main url works (mydomain.com/), but no matter what I type after the domain, I get a 404 error, I'm also not even sure how to properly diagnose the issue.

To my knowledge all the items in packages.json are installed on the server (I assume I'd get an error if they weren't), only difference is my local computer has NodeJS version 16, and my host provider has v10.

CodePudding user response:

In stead of using middleware (app.use()), you should use enter image description here

  •  Tags:  
  • Related