Out of boredom I currently try to create a simple chat-app on my localhost.
To start this all out, I began with a plain react app based on create-react-app.
In there I have the following code to start a WebSocket communication.
// on localhost:3000
componentDidMount = () => {
this.ws = new WebSocket('ws://127.0.0.1:5000');
this.ws.on('open', () => {
this.ws.send(this.props.userName + ' has joined the Chat.');
});
this.ws.on('message', (message) => {
const messages = this.state.messages;
this.state.messages.push(message)
this.setState({ messages: messages })
});
console.log('Component mounted.')
}
Whenever I try this at runtime with npm start
to communicate with the counterpart WebSocket server that looks like the following and started on the same machine with node server.js
// File: server.js
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 5000 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.send('something');
});
I get the following issue:
Access to fetch at 'http://127.0.0.1:5000/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
To solve this I've already tried:
- Access-Control-Allow-Origin extension for chrome no effect.
- To set the following proxy in package.json
proxy: http://localhost:5000
- also no effect. - As a kind of last resort I tried to launch google-chrome with
google chrome --disable-web-security --user-data-dir=/tmp
- in this case i get the following:GET http://127.0.0.1:5000/ net::ERR_ABORTED 426 (Upgrade Required)
and from here on I'm lost.
Can anyone help me out on this issue? Would this be possible in general or is there a flaw in my thinking?
I'm not a webdeveloper of anykind and usually do C++... Sorry if that all seems stupid.
Regards
Jack