Webpack dev server sockjs-node returns 404 error - webpack-dev-server

I am running a simple Vue app with webpack that I created with the vue-cli. When I run the dev server wtih npm run serve, it shows several errors in the client console when using sockjs-node. I believe this module is used by webpack for hot reloading (HMR).
The first error is:
Access to XMLHttpRequest at 'http://192.168.1.4:8080/sockjs-node/info?t=1615330207390' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I can solve this in two ways by editing the devServer in my vue.config.js. The first method is by setting public: 'localhost:8080'; and the second is by setting headers: {'Access-Control-Allow-Origin': 'http://192.168.1.4:8080', 'Access-Control-Allow-Credentials': 'true'}.
In both cases, I then see the following two errors:
POST http://localhost:8080/sockjs-node/690/qvgqwbdo/xhr_streaming?t=1615330686134 404 (Not Found)
GET http://localhost:8080/sockjs-node/690/zympwfsc/eventsource 404 (Not Found)
How do I resolve these errors so that the hot reloader will connect?

In the function I set to devServer.before in my vue.config.js file, I created my own websockets using Socket.io on the same port as my devSever. When the function returned, the devServer could not use that port for websockets, so it failed to launch sockjs-node. Therefore, when the frontend client tried to connect to the devServer, the requests were going to my sockets, instead of the devServer sockets, and it was ignoring them. Hence the 404 errors.
Here is my original code:
// server.js
const { createServer } = require('http')
const io = require('socket.io')
const addSocketEvents = require('./socket-api')
const port = process.env.PORT || 8080
module.exports = {
port,
configure(app) {
// `app` is an instance of express
// add the websockets
const httpServer = createServer(app)
socket = io(httpServer, {
path: '/socket-api'
})
addSocketEvents(socket)
// starts the server
// cannot use app.listen() because that will not start the websockets
httpServer.listen(port)
}
}
// vue.config.js
const { port, configure } = require('./server')
module.exports = {
devServer: {
before: configure,
public: `localhost:${port}`,
},
}
To fix this issue, I needed to allow the devServer to use the original port for sockjs-node, and launch my sockets on a different port. However, because I need to use the same port in production (due to restrictions by my current hosting provider), I only want my sockets to use a different port when running the devServer. To do this, I simply created a different httpServer and launched it on a different port, then created a proxy in the devServer config for that port. In my configure function, I just check to see if it is running in dev or prod, and act accordingly.
My production server is a simple express instance which calls the same configure function after it is created. This allows me to put all my startup code in one place.
Here is my new code:
// server.js
const { createServer } = require('http')
const io = require('socket.io')
const addSocketEvents = require('./socket-api')
const port = process.env.PORT || 8080
const proxyPort = 8081
module.exports = {
port,
proxyPort,
configure(app) {
// `app` is an instance of express
// add the websockets
let httpServer, socketPort
if (process.env.NODE_ENV === 'development') {
httpServer = createServer()
socketPort = proxyPort
} else {
httpServer = createServer(app)
socketPort = port
}
// adds the socket-api to be used via websockets
socket = io(httpServer, {
path: '/socket-api'
})
addSocketEvents(socket)
// starts the server
httpServer.listen(socketPort)
}
}
// vue.config.js
const { port, configure } = require('./server')
module.exports = {
devServer: {
before: configure,
public: `localhost:${port}`,
proxy: {
'/socket-api': {
target: `http://localhost:${proxyPort}`,
ws: true
}
}
},
}

Related

Vite serving shader file with wrong (none) MIME type

I'm developing a BabylonJS application. BabylonJS PostProcess class appends .fragment.fx to a given file name and requests that from the server. When my local Vite (version 4.0.4) dev server serves this file the content-type header is empty. This causes Firefox to intepret it as type xml and fail. Chrome fails through a different, but I think related, mechanism.
How do you configure Vite to serve the *.fragment.fx static files as text/plain? I assume I need to disable the default middleware and write some custom code instead, like this: https://vitejs.dev/config/server-options.html#server-middlewaremode but I wanted to first check there wasn't something else going on / a simpler way to configure / fix this.
The vite dev server is started using vite --host --port 3000 --force and the config in vite.config.js is:
import { defineConfig } from 'vite';
export default defineConfig(({ command, mode }) => {
// if (command === 'serve') {
// return {
// // dev specific config
// }
// } else {
// // command === 'build'
// return {
// // build specific config
// }
// }
return {
resolve: {
alias: {
"babylonjs": mode === "development" ? "babylonjs/babylon.max" : "babylonjs",
}
},
base: "",
// assetsInclude: ['**/*.fx'],
};
});
* edit 1 *
I have seen there's a parameter ?raw that can be added to the URL however I don't control how BabylonJS forms the URL so I can't see how to make this work in this situation.
I followed these instructions and set up a dev server using express. I added this block of code above the call to app.use(vite.middlewares):
app.use("**/*.*.fx", async (req, res, next) => {
const url = req.originalUrl
const file_path = path.resolve(__dirname, "." + url)
const file = fs.readFileSync(file_path, "utf-8")
res.status(200).set({ "Content-Type": "text/plain" }).end(file)
})
I now start the dev server using the following script line in the package.json of "dev": "node server",
I could not find a way to solve this by configuring the default vite dev server.

I request via mqtt protcol but my own browser request wss format

I want to make mqtt request to interact with my own broker . It should be done (client) using react or next.js and mqtt.js package.
I was attempt, but when I inspect a browser , It seems my browser attempt to ws connection and it currupt:
I was install this package :
npm i mqtt --save
Below are all stuffs which I attempt using these:
import React, { useEffect, useState } from "react";
import mqtt from "mqtt";
function Send() {
const [status, setStatus] = useState("Not Connect");
useEffect(() => {
//const client = mqtt.connect("wss://test.mosquitto.org:8081/mqtt");
const client = mqtt.connect("mqtt://171.22.25.40:1883");
client.on("connect", () => {
setStatus("Connect");
client.subscribe("IHS", (err) => {
if (!err) {
client.publish("IHS", "Test Message");
}
});
});
}, []);
return (
<div>
<p>{`Status: ${status}`}</p>
</div>
);
}
export default Send;
Is I missed an specific configuration for mqtt function ? How can I fix it?
Edit:
I append a configuration to mqtt variable like these snipped:
const options = {
port: 1883,
host: "171.22.25.40",
protocol: "mqtt",
keepalive: 10,
protocolId: "MQTT",
reconnectPeriod: 2000,
};
const client = mqtt.connect("mqtt://171.22.25.40:1883", options);
But nothing happened.
Edited:
I use this config in the mosquito config file, from C# can connect to mqtt but can't connect to wss
port 1883
listener 9001
protocol websockets
allow_anonymous true
You can not use native MQTT protocol from within the browser, because the browsers JavaScript sandbox will not allow you to make arbitrary TCP connections. You can only make HTTP or WS connections.
The MQTT.js package will always convert any mqtt:// URL to a ws:// when run in the browser.
You will need to make sure your broker is configured to accept MQTT over WebScoket connections and set the port number in the URL to match.

localhost:3000 This site can’t be reached after installing http-proxy-middleware

I am building a newsletter sign-up form that uses .netlify-lambda to send my form submission to Mailchimp. I installed http-proxy-middleware to help the front end find the netlify-lambda folder. After writing the proxy setup code below my React start script stopped working. It appears the proxy setup below is interfering with localhost:3000.
My proxy setup looks like this
const proxy = require('http-proxy-middleware');
module.exports = function(app) {
console.log('Using proxy...')
app.use(proxy('/.netlify/functions/', {
target: 'http://localhost:9000/',
"pathRewrite": {
"^\\.netlify/functions": ""
}
}));
};
If the target is localhost:9000 why is it interfering with localhost:3000?
When I start my Lambda server it says: Lambda server is listening on 9000.
I am also getting this error when trying to compile my client app.
crbug/1173575, non-JS module files deprecated
Short answer (for #lachnroll and anyone who might be encountering the same problem):
Please use const { createProxyMiddleware } = require("http-proxy-middleware") and app.use(createProxyMiddleware('/.netlify/functions/' ...)...) , instead of using const proxy = require('http-proxy-middleware'); and app.use(proxy("/.netlify/functions/" ...)...) , it should work.
Long one:
I've come across the same "can't be reached" thing in a React project when using http-proxy-middleware(2.0.3), until I changed const proxy = require('http-proxy-middleware'); and proxy("/.netlify/functions/" ...) to const { createProxyMiddleware } = require("http-proxy-middleware"); and app.use(createProxyMiddleware('/.netlify/functions/' ...)...) , I think the proxy has been removed, see: https://github.com/chimurai/http-proxy-middleware#readme

How to access backend after deploying website on Heroku?

My backend runs on port 5000 on localhost. So obviously when I connect to the backend from the frontend using const socket = io.connect('http://localhost:5000') others around the world will not be able to access it. I've deployed the React App on Heroku.
[https://murmuring-reaches-27066.herokuapp.com/]
Copy ID button isn't working because I don't understand how to connect to the backend when it's on production mode.
My Backend code (Only included relevant code)
const express = require("express")
const http = require("http")
const app = express()
const server = http.createServer(app)
const io = require("socket.io")(server, {
cors: {
origin: "https://murmuring-reaches-27066.herokuapp.com/",
methods: [ "GET", "POST" ]
}
})
Any help is appreciated.

Websockets, truffle, ganache and react setup issues connection not open on send()

Sometimes I refresh, and it works. Sometimes it just doesn't work.
I tried changing ganache GUI settings to use port 8545 which I read is the WebSockets port but it still won't connect. ws:127.0.0.1 won't work and neither will http://
This is my truffle config file. The rest of the code is large and won't help much.
// See <http://truffleframework.com/docs/advanced/configuration>
// #truffle/hdwallet-provider
// var HDWalletProvider = require("truffle-hdwallet-provider");
const path = require("path");
var HDWalletProvider = require("#truffle/hdwallet-provider");
module.exports = {
// See <http://truffleframework.com/docs/advanced/configuration>
// to customize your Truffle configuration!
// contracts_directory: "./allMyStuff/someStuff/theContractFolder",
contracts_build_directory: path.join(__dirname, "/_truffle/build/contracts"),
// migrations_directory: "./allMyStuff/someStuff/theMigrationsFolder",
networks: {
ganache: {
host: "127.0.0.1",
port: 7545,
//port: 8545,
network_id: 5777,
//network_id: "*", // Match any network id,
websockets: false, // websockets true breaks TODO: connection not open on send()
// wss
},
},
};
This is some of my code on the actual screen in question.
const options = {
web3: {
block: false,
fallback: {
type: 'ws',
//url: 'ws://127.0.0.1:8546',
url: 'http://127.0.0.1:7545',
},
},
contracts: [MyStringStore],
// polls: {
// accounts: IntervalInMilliseconds,
// },
events: {},
};
I don't understand why sometimes it works and I can see drizzle state and sometimes I can't. React native and web3 is very new to me.
I get errors like this:
00:06 Contract MyStringStore not found on network ID: undefined
Error fetching accounts:
00:06 connection not open
I am having real difficulty setting up drizzle as well. One thing I see is that your
url: 'http://127.0.0.1:7545',
For some reason Drizzle only works with 'ws' as the prefix for such a URL. I am trying to follow this guide by people who got it working.
I think websocket is only available in the command line version.
Try install and use ganache-cli instead of the gui version.

Resources