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.
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.
Part of Web servers
- Create your serverP
- Create your appP
- Node and the terminalP
- More about the terminalP
- Web frameworksP
- Using ExpressP
- Serving static files
- Views and templates
- Routing
- Real data
- Includes
- Get confident with Express
- Build your app in ExpressP