2 ms·
That's not true. You can talk to any other origin with ws. Simple example: index.html: <html> <head></head> <body> <div id="message"></div>
by oefrha 6y ago
That's not true. You can talk to any other origin with ws. Simple example:
index.html:
<html>
<head></head>
<body>
<div id="message"></div>
<script>
let ws = new WebSocket("ws://localhost:5000/");
ws.onopen = () => ws.send("hello server!");
ws.onmessage = ev => {
const $message = document.getElementById("message");
$message.textContent = `ws://localhost:5000/ response: ${ev.data}`;
};
</script>
</body>
</html>
server.js:
const express = require("express");
const http = require("http");
const WebSocket = require("ws");
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
wss.on("connection", ws => {
ws.on("message", message => {
console.log(`received: ${message}`);
ws.send("hello client");
});
});
server.listen(5000, () => console.log("ws server listening on localhost:5000"));
Server runs on localhost:5000. Now serve index.html from any other origin and see it talk to the server without any problem.