skip to Main Content

I am fairly new to express.js , so the question might be easy , but I cannot fix it for almost 4 hours.

I have my express server that should be returning a build of react app. I am using useragent lib to return the app if a user is not bot.

The code is pretty simple.

const express = require('express');
const {PORT, CLIENT_URL} = require('./constants');
const app = express();
const cookieParser = require('cookie-parser');
const passport = require('passport');
const cors = require('cors');
const useragent = require('express-useragent');

app.use(express.static("public/dist"));
app.use(useragent.express());
app.use(express.json());
app.use(cookieParser());
app.use(cors({ origin: CLIENT_URL, credentials:true }))

app.use('/api',authRoutes); //here are my api routes

app.get("/connect",async (req,res)=> {
    console.log(req.useragent.isBot)
    if (req.useragent.isBot == false){
    try{
        res.sendFile(path.resolve(__dirname,"..","public","dist","index.html"));
    } catch(err){
        res.json({
            "Error": "ERROR",
            "status": err
        })
    }
} else {
    try {
        res.status(403)     
    } catch (error) {
        res.status(403);   
    }
 }
})



const appStart = () => {
    try {
        app.listen(PORT , () => {
            console.log(`The app is running at http://localhost:${PORT}`);
        });
    } catch (error){
        console.log(`Error: ${error.message}`);
    }
};

appStart();

the folder structure is :
—project –public – dist
–src – index.js

So the PROBLEM is : when i connect to http://localhost:8080/connect it works well and returns the app as it should, but it does the same when I connect to http://localhost:8080/ without bot filter and I dont want it. I know that the problem is here app.use(express.static("public/dist")); , but I have no idea how to change it. I tried to remove this line , it works , but fails to load some of the assets for some reason. I have also removed dist from public but it didn’t help

Something like

app.use('/', async (req,res) => {
    res.json({
        "status": 403 
    })
    
})

blocks the whole app. Please help 🙂

3

Answers


  1. Change this

    app.use('/', async (req,res) => {
        res.json({
            "status": 403 
        })  
    })
    

    to

    app.get('/', async (req,res) => {
        res.json({
            "status": 403 
        })  
    })
    
    Login or Signup to reply.
  2. const express = require('express');
    const { PORT, CLIENT_URL } = require('./constants');
    const app = express();
    const path = require('path');
    const cookieParser = require('cookie-parser');
    const passport = require('passport');
    const cors = require('cors');
    const useragent = require('express-useragent');
    
    app.use(useragent.express());
    app.use(express.json());
    app.use(cookieParser());
    app.use(cors({ origin: CLIENT_URL, credentials: true }));
    
    app.use('/api', authRoutes); // Your API routes go here
    
    app.get('/connect', (req, res) => {
      console.log(req.useragent.isBot);
      if (!req.useragent.isBot) {
        try {
          res.sendFile(path.resolve(__dirname, '..', 'public', 'dist', 'index.html'));
        } catch (err) {
          res.json({
            Error: 'ERROR',
            status: err,
          });
        }
      } else {
        try {
          res.status(403).send('Forbidden');
        } catch (error) {
          res.status(403).send('Forbidden');
        }
      }
    });
    
    app.listen(PORT, () => {
      console.log(`The app is running at http://localhost:${PORT}`);
    });

    Here’s what has changed:

    The app.use(express.static("public/dist")); line is removed from the code. This ensures that the static files from the public/dist directory will not be served by default for all routes.

    The /connect route is added to handle the request for the React app when the user agent is not a bot. The res.sendFile method is used to send the index.html file from the public/dist directory.

    The app.listen method is moved outside the app.get(‘/connect’, …) route. This ensures that the server is started and listening on the specified port.

    With these changes, the React app build will be served only when accessing the /connect route. For the root URL (http://localhost:8080/), the default behavior will be applied, which could be sending a different response or handling it in another route based on your requirements.

    Login or Signup to reply.
  3. Whenever you are using app.use('/', router) the second parameter must be a router. For your particular scenario you can use `app.get(). Update your code as below:

    app.get('/', async (req,res) => {
        res.json({
            "status": 403 
        })
        
    })
    

    Also, remove the line:

    app.use(express.static("public/dist"))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search