0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

POSTリクエストで受け取ったJSONデータをWebsocketに送信する

Last updated at Posted at 2019-08-14

#概略
POSTリクエストをWebsocketに流したいときに使うコンバータのようなものです。
##必要なもの

  • node.js
  • Express
  • body-parser

いずれも最新版を使います。

#ソースコード

app.js
//expressの各種定義
const express = require('express');
const body_parser = require('body-parser');
const app = express();

//websocketの定義
var server = require('ws').Server;
var ws_server = new server({ port: 3001 });

// urlencodedとjsonは別々に初期化
app.use(body_parser.urlencoded({
    extended: true
}));
app.use(body_parser.json());

//サーバーの立ち上げ
app.listen(3000);
console.log('HTTP Server is online.');

//json_dataの定義
var json_data = null;

//postリクエストの受け取り
app.post('/', function(req, res) {
    json_data = req.body;
    //コンソールに受け取ったjsonを表示
    console.log(json_data);
    //websocketに投げる
    ws_server.clients.forEach(function(client){
        client.send(JSON.stringify(json_data));
    })
    res.send('POST request convert to websocket');
});

githubにも公開しています。

##参考
https://qiita.com/ktanaka117/items/596febd96a63ae1431f8

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?