How to use the express-ws function in express-ws

To help you get started, we’ve selected a few express-ws examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github NERDDISCO / luminave / server / core / ExpressServer.js View on Github external
constructor(param) {

    this.port = param.port || 3000;
    this.config = param.config;
    this.app = express();

    // Create HTTP server
    this.server = http.createServer(this.app);

    this.server.listen(this.config.server.port);
    this.server.on('error', this.onError.bind(this));
    this.server.on('listening', this.onListening.bind(this));

    //const index = require('./routes/index');

    let express_ws = expressWs(this.app, this.server, {
      perMessageDeflate: false
    });
    this.app = express_ws.app;

    // view engine setup
    this.app.set('views', path.join(__dirname, '../../client-bin/views'));
    this.app.set('view engine', 'jade');

    // uncomment after placing your favicon in /public
    //this.app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
    //this.app.use(logger('dev'));
    this.app.use(bodyParser.json());
    this.app.use(bodyParser.urlencoded({ extended: false }));
    this.app.use(cookieParser());
    this.app.use(express.static(path.join(__dirname, '../../client-bin')));
github Exynize / exynize-rest / src / server.js View on Github external
// compile client code
import './client';

// init app
const app = express();
// parse request bodies (req.body)
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
// support _method (PUT in forms etc)
app.use(methodOverride());
// enable CORS headers
app.use(cors());
// enable CORS pre-flights
app.options('*', cors());
// enable websockets on routes
expressWs(app);
// error handling inside of express
app.use((err, req, res, next) => { // eslint-disable-line
    logger.error(err.stack);
    res.status(500).send('Something broke!');
});
// static files
const staticPrefix = process.env.NODE_ENV === 'production' ? '/api' : '';
app.use(staticPrefix + '/static', express.static(join(__dirname, 'static')));
// output all uncaught exceptions
process.on('uncaughtException', err => logger.error('uncaught exception:', err));
process.on('unhandledRejection', error => logger.error('unhandled rejection:', error));


// setup api
// users & auth
setupUsers(app);
github OriginProtocol / origin / origin-linking / src / index.js View on Github external
import '@babel/polyfill'
import express from 'express'
import cookieParser from 'cookie-parser'
import expressWs from 'express-ws'
import useragent from 'express-useragent'
import cors from 'cors'
import bodyParser from 'body-parser'
import morgan from 'morgan'
import 'express-async-errors'

const app = express()
expressWs(app)
app.use(cookieParser())
app.use(morgan('combined'))
app.use(useragent.express())
app.use(cors({ origin: true, credentials: true }))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))

import linkerRoutes from './linker-routes'

const port = 3008

app.use('/api/wallet-linker', linkerRoutes)

app.listen(port, () => console.log(`Linking server listening on port ${port}!`))

export default app
github arackaf / booklist / startApp.js View on Github external
res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Authorization, Content-Type, Accept");
  next();
});

app.use(
  "/graphql-public",
  expressGraphql({
    schema: executableSchemaPublic,
    graphiql: true,
    rootValue: rootPublic
  })
);

const expressWs = expressWsImport(app);

app.use("/static/", express.static(__dirname + "/static/"));
app.use("/node_modules/", express.static(__dirname + "/node_modules/"));
app.use("/react/", express.static(__dirname + "/react/"));
app.use("/utils/", express.static(__dirname + "/utils/"));
app.use("/uploads/", express.static(__dirname + "/uploads/"));

app.ws("/bookEntryWS", function(ws, req) {
  bookEntryQueueManager.subscriberAdded(req.user.id, ws);
});

easyControllers.createAllControllers(app, { fileTest: f => !/-es6.js$/.test(f) }, { __dirname: "./node" });

app.use("/compare/react/", express.static(__dirname + "/compare/react/"));
app.get("/compare/react", (req, res) => {
  res.sendFile(path.join(__dirname + "/compare/react/dist/index.html"));
github wspl / DanmakuChi-Server-Node / src / Server.js View on Github external
import Express from 'express';
import ExpressWebSocket from 'express-ws';
import childProcess from 'child_process';
import Wechat from './Wechat';
import Config from './Config';
import { SocketProxy, SocketMiddleware } from './Socket';

const app = new Express();

ExpressWebSocket(app);

app.get('/', function (req, res) {
  res.end('test');
});

let socketProxy = SocketProxy();

app.use('/wechat_api', Wechat(socketProxy));
app.ws('/ws', SocketMiddleware(socketProxy));

app.listen(Config.web.listenPort, () => {
  console.log('Server is running...');
});
github rbelouin / fip.rbelouin.com / src / server / index.ts View on Github external
import path from "path";
import express from "express";
import expressWs from "express-ws";
import Bacon from "baconjs";
import * as Sentry from "@sentry/node";

import config from "../../prod/js/config.json";
import { fetchRadios } from "../fip/radio-metadata";
import { spotifyLogin, spotifyCallback } from "../spotify/auth";

Sentry.init({
  dsn: process.env.SENTRY_DSN
});

const app = express();
expressWs(app);

const apiPrefix = "/api";
const publicFolder = process.env.PUBLIC_FOLDER || "";
const httpsOnly = process.env.HTTPS_ONLY === "1";
const spotifyConfig = {
  clientId: process.env.SPOTIFY_CLIENT_ID || "",
  clientSecret: process.env.SPOTIFY_CLIENT_SECRET || "",
  loginPath: "/api/login",
  callbackPath: "/api/callback"
};

app.use(function(req, res, next) {
  const protocol =
    req.headers["x-forwarded-proto"] === "https" ? "https" : "http";

  if (httpsOnly && protocol !== "https") {
github embark-framework / embark / src / lib / modules / api / server.ts View on Github external
private initApp() {
    const instance = expressWs(express());
    instance.app.use((req: Request, res: Response, next: NextFunction) => {
      if (!this.isLogging) {
        return next();
      }

      if (!req.headers.upgrade) {
        this.embark.logger.info(`API > ${req.method} ${req.originalUrl}`);
      }
      next();
    });

    instance.app.use(helmet.noCache());
    instance.app.use(cors());

    instance.app.use(bodyParser.json());
    instance.app.use(bodyParser.urlencoded({extended: true}));
github seekwhencer / node-radio-automation / app / lib / Api / Websocket.js View on Github external
constructor(args) {
        super(args);
        this.router = EXPRESS.Router();
        this.epressWs = expressWs(APIAPP, null, {
            wsOptions: {
                verifyClient: (info, cb) => {
                    let token = info.req.headers.authorization;
                    if (!token) {
                        cb(false, 401, 'Unauthorized');
                    } else {
                        if (token.startsWith('Bearer ')) {
                            token = token.slice(7, token.length);
                        }
                        jwt.verify(token, this.options.secret, (err, decoded) => {
                            if (err) {
                                cb(false, 401, 'Unauthorized');
                            } else {
                                info.req.user = decoded;
                                cb(true)
                            }
github embark-framework / embark / packages / stack / api / src / server.ts View on Github external
private initApp() {
    const instance = expressWs(express());
    instance.app.use((req: Request, _res, next: NextFunction) => {
      if (!this.isLogging) {
        return next();
      }

      if (!req.headers.upgrade) {
        this.embark.logger.info(`API > ${req.method} ${req.originalUrl}`);
      }
      next();
    });

    instance.app.use(helmet.noCache());
    instance.app.use(cors());

    instance.app.use(bodyParser.json());
    instance.app.use(bodyParser.urlencoded({ extended: true }));

express-ws

WebSocket endpoints for Express applications

BSD-2-Clause
Latest version published 3 years ago

Package Health Score

56 / 100
Full package analysis

Popular express-ws functions