Home > database >  how to run node app.js on production environment?
how to run node app.js on production environment?

Time:09-27

I am using express and hosting my website on Cloudflare. It work well on localhost by command node app.js but when I publish it to cloudflare, only index.html is showing. Whenever I change the url to https://domainname/api/users or https://domainname/api/users/1, it is still showing index.html. I have tried on Insonmia to request GET from https://domainname/api/users but the response is index.html. Everything work well on localhost.

Here is my code on app.js

const express = require('express');
const app = express();

app.use(express.json());

const port = process.env.PORT || 3000;
app.listen(port, () => {
    console.log(`Our express server is up on port ${port}`);
});

const users = [
    { id: 1, name: 'user1' },
    { id: 2, name: 'user2' },
    { id: 3, name: 'user3' },
];

app.get('/', (req, res) => {
    res.sendFile(__dirname   '/index.html');
});

app.get('/api/users', (req, res) => {
    res.send(users);
});

app.get('/api/users/:id', (req, res) => {
    const user = users.find((c) => c.id === parseInt(req.params.id));
    if (!user) res.status(404).send('Error 404: Users not found.');
    res.send(user);
});

index.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    </meta>
    <title>hello</title>
    <script src="script.js"></script>
</head>

<body>
    <h2>hello world</h2>
</body>

</html>

package.json

{
  "dependencies": {
    "express": "^4.18.1"
  },
  "name": "hello",
  "description": "",
  "version": "1.0.0",
  "main": "app.js",
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

CodePudding user response:

You can try adding node app.js to start script in package.json. (So your hosting service (cloudfare) will run that script to start your project.)

Try the following code in your package.json:

{
  "dependencies": {
    "express": "^4.18.1"
  },
  "name": "hello",
  "description": "",
  "version": "1.0.0",
  "main": "app.js",
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",

    "start": "node index.js"

  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

I hope this helps.

CodePudding user response:

try adding new script called "start": "node index.js" to your package.json.
This resolve your problem!

CodePudding user response:

Take this answer with a grain of salt - it’s been over a year since I’ve written an express app as I am now a frontend dev, but I do recall having a similar issue in bootcamp.

It is likely the order of your routes. I believe they will be read from top to bottom and the first match will be executed, if I remember correctly. It is not like the new version of React Router (if you code in React as well) where it will first look for exact matches.

Try flipping the order of your three routes at the bottom around, like this:

const express = require('express');
const app = express();

…

app.get('/api/users/:id', (req, res) => {
    const user = users.find((c) => c.id === parseInt(req.params.id));
    if (!user)         res.status(404).send('Error 404: Users not found.');
    res.send(user);
});

app.get('/api/users', (req, res) => {
    res.send(users);
});

app.get('/', (req, res) => {
    res.sendFile(__dirname   '/index.html');
});

The way your Express server is written now, it’s always going to serve up the index.html file because every endpoint begins with ‘/‘ and it will stop reading the rest of the url as soon as it finds a match. With get(‘/‘) as your first route in the file, it’ll always trigger that route because every endpoint begins with it. By starting with the most granular of routes, each one will be a no-match until it gets to the correct one, and you should be able to hit all 3 endpoints.

  • Related