Express and NodeJs Two Methods of Creating Server

  • 2021-07-16 01:43:20
  • OfStack

Directory

NodeJs Create Web Server Express Create Web Server

NodeJs Create Web Server


var http = require('http');
var server = http.createServer(function(req, res) {
 res.writeHead(200, {
  'Content-Type': 'text/plain'
 });
 res.write('hello world!');
 res.end();
 }).listen(80);

This is a native way to create an web server, but it is flawed. If we want to put our static pages in the same domain as the server, it is very inconvenient.

Express Create an Web Server


var express = require('express');
var app = express();
var server = require('http').createServer(app);
// Specify the location of static files 
app.use('/', express.static(__dirname + '/public')); 
// Listening port number 
server.listen(80);

Here, we use the encapsulated method of Express to create a method to listen to port 80, which can not help but be accessed as a back-end service through localhost: 80, and can also access our front-end page localhost: 80/index. html.

In this way, the interaction between the page and the server is much more convenient.


Related articles: