0

This is my first experience with Node.js.

Using an ubuntu ec2 instance on which I have installed Node, I am following this tutorial: https://blog.logrocket.com/setting-up-a-restful-api-with-node-js-and-postgresql-d96d6fc892d8/

My index.js file looks like this:

const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const port = 22

app.use(bodyParser.json())
app.use(
  bodyParser.urlencoded({
    extended: true,
  })
)

app.get('/', (request, response) => {
  response.json({ info: 'Node.js, Express, and Postgres API' })
})

app.listen(port, () => {
  console.log(`App running on port ${port}.`)
})

When I get to the part where I run node index.js, I get this error:

ubuntu@ip-172-31-87-85:~/riapi$ node index.js 
events.js:183
      throw er; // Unhandled 'error' event
      ^

Error: listen EACCES 0.0.0.0:22
    at Object._errnoException (util.js:1022:11)
    at _exceptionWithHostPort (util.js:1044:20)
    at Server.setupListenHandle [as _listen2] (net.js:1350:19)
    at listenInCluster (net.js:1408:12)
    at Server.listen (net.js:1492:7)
    at Function.listen (/home/ubuntu/riapi/node_modules/express/lib/application.js:618:24)
    at Object.<anonymous> (/home/ubuntu/riapi/index.js:17:5)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)

I found this SO issue: ExpressJS - throw er Unhandled error event

And when I tried a couple things from it, but without success:

ubuntu@ip-172-31-87-85:~/riapi$ netstat -tulnp | grep 22
(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      -                   
tcp6       0      0 :::22                   :::*                    LISTEN      -                   
ubuntu@ip-172-31-87-85:~/riapi$ ps aux | awk '/node/{print $2}' | xargs kill -9
kill: (20586): No such process

Does anyone see what I'm doing wrong?

LevelChart8
  • 207
  • 1
  • 8

1 Answers1

1

As mentioned in the comments, port 22 requires root privileges and is usually reserved for SSH.

Try replacing const port = 22 by const port = 8080 (port 8080 is the official HTTP alternate port).

Any unused port over 1024 should work (see https://unix.stackexchange.com/questions/16564/why-are-the-first-1024-ports-restricted-to-the-root-user-only).

sunknudsen
  • 6,356
  • 3
  • 39
  • 76