Return String

Express 4: Basic Server

Updated 2021-03-07

Run npm install express to install Express.

This basic Express application accepts a GET requests at our root: / on port 8080. We can run the server with node filename.js and connect to localhost:8080 with a browser. Our server should respond with hello world! which will be displayed in the browser.

const express = require('express');
const http = require('http');

// Environment variables
const PORT = 8080;

// Set up Express application
const app = express();
app.get('/', getHandler);

// Create HTTP server
http.createServer(app).listen(PORT, () => {
    console.log(`listening on ${PORT}...`);
});

// Sends Response with hello world!
function getHandler(req, res) {
    res.status(200).type('text/plain').send('hello world!');
}