DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Creating a Secure REST API in Node.js
  • Node.js Http Module to Consume Spring RESTful Web Application
  • Leveling Up My GraphQL Skills: Real-Time Subscriptions
  • Building and Integrating REST APIs With AWS RDS Databases: A Node.js Example

Trending

  • Introduction to Retrieval Augmented Generation (RAG)
  • Security by Design: Building Full-Stack Applications With DevSecOps
  • IoT and Cybersecurity: Addressing Data Privacy and Security Challenges
  • How GitHub Copilot Helps You Write More Secure Code
  1. DZone
  2. Coding
  3. JavaScript
  4. Static Content, REST Endpoints, and WebSockets With Express and Node.js

Static Content, REST Endpoints, and WebSockets With Express and Node.js

Express is a simple framework for developing REST endpoints. See how to serve static content, REST endpoints, and WebSockets with Express and Node.js.

By 
Kevin Hooke user avatar
Kevin Hooke
·
Apr. 05, 17 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
17.6K Views

Join the DZone community and get the full member experience.

Join For Free

I’ve yet to see a framework that is as simple as Express for developing REST endpoints. I’m experimenting with a React app that receives push updates from the server using Websockets. Is it possible to use Express to serve all the requests for this app: static content (the React app), REST endpoints. and Websocket? Turns out, yes — and it’s pretty easy, too.

Starting first using Express to serve static content:

var express = require('express');

//init Express
var app = express();

//init Express Router
var router = express.Router();
var port = process.env.PORT || 8080;

//connect path to router
app.use("/", router);
app.use(express.static('static'))
var server = app.listen(port, function () {
    console.log('node.js static server listening on port: ' + port)
})

This uses the static middleware for serving the static content.

Handling REST requests with Express is simple using the get(), post(), put(), and delete() functions on the Router. Adding an example for a GET for /status, now we have this:


var express = require('express');

//init Express
var app = express();

//init Express Router
var router = express.Router();
var port = process.env.PORT || 8080;

// GET /status
router.get('/status', function(req, res) {
    res.json({ status: 'App is running!' });
});

//connect path to router
app.use("/", router);
app.use(express.static('static'))

var server = app.listen(port, function () {
    console.log('node.js static content and REST server listening on port: ' + port)
})

Next, add support for Websockets using the ws library. Incrementally adding to the code above, now we create a WebSocket.Server, using the option to pass in the already created HTTP server: const wss = new SocketServer({ server });.

At this point, we add callbacks for connection and message events, and we’re in business:

const SocketServer = require('ws').Server;
var express = require('express');
var path = require('path');
var connectedUsers = [];

//init Express
var app = express();

//init Express Router
var router = express.Router();
var port = process.env.PORT || 80;

//return static page with websocket client
app.get('/', function(req, res) {
    res.sendFile(path.join(__dirname + '/static/index-with-websockets.html'));
});

var server = app.listen(port, function () {
    console.log('node.js static server listening on port: ' + port + ", with websockets listener")
})

const wss = new SocketServer({ server });

//init Websocket ws and handle incoming connect requests
wss.on('connection', function connection(ws) {
    console.log("connection ...");

    //on connect message
    ws.on('message', function incoming(message) {
        console.log('received: %s', message);
        connectedUsers.push(message);
    });

    ws.send('message from server at: ' + new Date());
});

This is the starting point for a React app to build a WebSockets client — more on that in a future post. The code so far is available in this GitHub repo.

REST Web Protocols Express WebSocket Node.js

Published at DZone with permission of Kevin Hooke, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Creating a Secure REST API in Node.js
  • Node.js Http Module to Consume Spring RESTful Web Application
  • Leveling Up My GraphQL Skills: Real-Time Subscriptions
  • Building and Integrating REST APIs With AWS RDS Databases: A Node.js Example

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!