0

This Link is explaining difference with app.use and app.get. But not explaining about same route problem. So I want to ask my question.

I made react project with create-react-app and make server inside src folder. I want to show text in the index.html when url is root. So I write codes like this.

public/index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="theme-color" content="#000000">
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    <title>React App</title>
  </head>
  <body>

    <p>Html test</p>

  </body>
</html>

src/server/server.js

import express from 'express';
import path from 'path';

const app = express();
const port = 4000;

app.use('/', express.static(path.join(__dirname, '../../public')));

app.get('/', (req, res) => {
    return res.send('<p>Hello index</p>');
});

app.get('/hello', (req, res) => {
    return res.send('Hello CodeLab');
});

app.listen(port, () => {
    console.log('Express is listening on port', port);
});

package.json

"babel-node": "babel-node src/server/server.js --presets es2015"

I test,

localhost:4000/hello --> Hello CodeLab

localhost:4000/ --> Html test (not Hello index)

I thought app.use is just static file which called every time when same url is called by app.get. Why app.get('/')doesn't show <p>Hello index</p> in this project?

SooJungChae
  • 219
  • 1
  • 4
  • 16

2 Answers2

1

Why app.get('/') doesn't show <p>Hello index</p> in this project?

It depends on the order. Re-write like this:

app.get('/', (req, res) => {
    return res.send('<p>Hello index</p>');
});
app.use('/', express.static(path.join(__dirname, '../../public')));

You will get <p>Hello index</p> for sure!

The reason is under the hood, app.use() and app.get() both behave just like middlewares, they are treated equally in the Express app. The appear order decides which one is executed first.

You Nguyen
  • 9,961
  • 4
  • 26
  • 52
0

an app is an object initialized on the start of express. app.use is for setting midleware More info

to resolve this problem just remove match for a route:

app.use(express.static(path.join(__dirname, '../../public')));

With '/' in app.use you must use next() method then express will go to next controller.

Lukasz Migut
  • 192
  • 1
  • 3
  • 9