codeDragon
codeDragon

Reputation: 565

How to open localhost when you listen to port 80 in node.js?

I am currently starting out in node.js and I want to open my server.js file in localhost. What is the URL directory path for that, as I have noticed you don´t need the foldername where the file is located in as in Apache.

But I am not sure. Otherwise my directory is the following Desktop/node-projects/exercise-node-mongo/server.js

Upvotes: 0

Views: 2275

Answers (1)

Ashleigh Carr
Ashleigh Carr

Reputation: 76

Node.js is not explicitly made for running web applications, you need to create the web server using your own code in Node.js

A popular framework for running a website on Node.js is Express which can be installed simply by opening command prompt in the folder you have stored server.js in and run the following steps:

  1. Run the command npm install express to install express
  2. Edit server.js in your favourite editing program(notepad)
  3. Insert the following code

    const express = require('express')
    const app = express()
    const port = 3000
    
    app.get('/', (req, res) => res.send('Hello World!'))
    app.listen(port, () => console.log(`Example app listening on port ${port}!`))
    
  4. Run the app by running node server.js from the command prompt

  5. Open localhost:3000 in your browser and you should see the text Hello World! appear

You should look at the guides for express to learn more on how it all works https://expressjs.com/en/starter/hello-world.html

Upvotes: 2

Related Questions