Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialChristoph Ruepprich
2,887 PointsI have seen examples where express.js is used with http. Instead of app.listen(3000), an http server is created. Why?
Example from http://bit.ly/2ktVtIq http://bit.ly/2jCNIAr var express = require('express'); var http = require('http'); var app = express();
app.use(app.router);
app.get('/', function (req, res, next) { console.log(req.socket.server); });
app.server = http.createServer(app); app.server.listen(3000);
What is the purpose of creating app.server?
4 Answers
Michael Liendo
15,326 Pointsgood question. The short answer is that Express is "unopinionated" meaning that it doesn't care how you set it up. It's kind of nice because it gives versatility, but as you've noticed, the downside is that it doesn't help in creating a standard. In regards to your specific code, one way to set up express is to use it's build in methods to create the server. I prefer this way because I can bootstrap a server in 4 lines of code:
const express = require('express')
const app = express()
app.get('/',(req,res) => res.send('Hello')
app.listen(3000,() => console.log('express app listening on port 3000')
But someone not completely familiar with express can fall back to using Node built in server module "HTTP" and "HTTPS" to build their server.
Christoph Ruepprich
2,887 PointsThanks Michael, but what does http have that express doesn't?
Michael Liendo
15,326 PointsNothing. But some prefer less frills so they stick what they learned first/ are more accustomed to using. Another reason why express is so popular, it caters to lots of personal preferences.
Christoph Ruepprich
2,887 PointsThanks for the info. Cheers!
Christopher Debove
Courses Plus Student 18,373 PointsFor example you could attach a socket server to this http server.
Express is built on top of an http server. But what if you would like to manipulate the server itself?