-1

I'm trying to create a simple backend api for an app I'm working on (create-react-app) and decided to use node express. I'm getting the error 'cannot GET' when I open my browser and I don't understand why.

Here is my server/index.js file:

const express = require("express");

const PORT = process.env.PORT || 3001;

const app = express();

app.get("/api", (req, res) => {
    res.json({ message: "Hello from server!" });
  });
  
  app.listen(PORT, () => {
    console.log(`Server listening on ${PORT}`);
  });

app.listen(PORT, () => {
  console.log(`Server listening on ${PORT}`);
});

Here is my start script:

"scripts": {
    "start": "node index.js"
  }

In my console I see this error:

Failed to load resource: the server responded with a status of 404 (Not Found)

This is my folder structure: I have an app called 1REPMAX that contains the folders

>build
>node-modules
>public
>server
   >node_modules
   >index.js
   >package-lock.json
   >package.json
>src
.gitignore
package-locj.json
package.json

So what I've been doing is I cd into server and then run npm start.

When I open my browser to localhost:3001 I get the error. Any help on what I'm doing wrong? If more information is needed just let me know. Also, when I ran npm start the first time it started up fine, but now every time I run it I get this error:

code: 'EADDRINUSE',
  errno: -48,
  syscall: 'listen',
  address: '::',
  port: 3001

I don't know if this has something to do with it or not.

Victor
  • 329
  • 4
  • 17
  • Does this answer your question? [static files with express.js](https://stackoverflow.com/questions/10434001/static-files-with-express-js) – theusaf Aug 24 '21 at 19:58

1 Answers1

1

The first error is caused because your app is not listening to the / path, only the /api path.

The second error is caused by a duplicate app.listen() call in your server/index.js file.

Your code should look something like this in order to resolve the issues:

const express = require("express");
const PORT = process.env.PORT || 3001;
const app = express();

app.get("/", (req, res) => res.send("Main page")); 

app.get("/api", (req, res) => {
  res.json({ message: "Hello from server!" });
});
  
app.listen(PORT, () => {
  console.log(`Server listening on ${PORT}`);
});
theusaf
  • 1,781
  • 1
  • 9
  • 19
  • Thank you for your response. I tried your code and I'm getting the same error. It could possibly be an error somewhere else in my code? – Victor Aug 24 '21 at 19:19
  • Do both errors still happen, or just the GET error? – theusaf Aug 24 '21 at 19:26
  • both still happen. I updated my question to show my folder structure and what I do before running npm start. – Victor Aug 24 '21 at 19:41