Baz Baz - 1 year ago 79
Node.js Question

"Cross origin requests are only supported for HTTP." with Node.js

The following code in my client App:

const socket = io('${location.protocol}//${location.hostname}:8090');

is giving me the following error in my browser:

XMLHttpRequest cannot load http://${location.protocol}/ Cross origin requests are only supported for HTTP.

My client code is run using Node.js via
npm start
so "http://localhost:3000" is automatically refreshed in my browser as I update my code.

Answer Source

It appears that ${location.protocol} is not being substituted for in the string and thus it's still in the URL when tries to use the URL. This could be because the browser does not support that specific ES6 feature.

You can work around it by constructing your URL string the old fashioned way with string addition.

const socket = io(location.protocol + '//' + location.hostname + ':8090');

And, you should also be using backticks as the string delimiters if you expect the substitution to work reliably where it is supported.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download