BETAThis is a new service – your feedback will help us to improve it.

Using Express

Now that we've installed Express, it's time to start writing our app's server code.

First we're going to configure Express.

From the projects explorer, delete the hello.js file we used earlier and create a new blank file called server.js.

In server.js, write the following:

const express = require('express')

let server = express()

server.use(express.static(__dirname + '/static'))

server.listen(3000, function(){
    console.log("Server is running")
})

The first line makes Express available to use in our code, saving it as a variable.

The second line takes the Express code and runs it.

The third line will be explained in the next lesson.

The final block of code makes Express available on the internet.

Running the app

We're now ready to run our app for the first time. It won't do much yet, but we can check that Express is installed and configured successfully.

We can run our app by typing node server like earlier, but this will cause trouble.

Codenvy has many servers, and many apps on each server. That's a lot of potential URLs. We have no way of knowing which URL we need to put into our browser to see our own app. We need Codenvy to tell us.

On the left hand side of the screen, select the "commands" tab to open the commands explorer.

Under the "RUN" section, click the plus icon to add a new command, and click custom.

In the box that appears, give the command a name of "Start".

In the Command Line box, type:

node my-app/server

In the Preview URL box, type:

http://${server.port.3000}

You don't need to change anything else.

We've now told Codenvy how to start our app, and asked for the URL we need to visit it on the web.

You can now run your app by clicking the blue play icon at the top centre of the screen.

Run your app now. You should see a message in the terminal that looks something like this:

command: node my-app/server
preview: http://node11.codenvy.io:47586
Server is running

You can click the preview URL to visit your app on the web.

In the webpage that appears, you should see an error:

Cannot GET /

That's what we want to see, because this is an error generated by Express—seeing it proves that Express is working.

In the next lesson, we'll discuss what this error means and how to make Express do useful things.

Make sure that you can run your app by clicking the play button, and can visit it on the web, before continuing.
Lessons last updated 12th July 2019. You can improve this lesson on Github.
Part of Web servers
  1. Create your serverP
  2. Create your appP
  3. Node and the terminalP
  4. More about the terminalP
  5. Web frameworksP
  6. Using ExpressP
  7. Serving static files
  8. Views and templates
  9. Routing
  10. Real data
  11. Includes
  12. Get confident with Express
  13. Build your app in ExpressP