Proxy Issue ENOTFOUND Create-React-App Http-Proxy-Middleware Express - node.js

I've run into a new problem when proxy my client requests from CRA to my express API server when in development.
I get the following error message from HPM. And I can see it returns as 504 Gateway Timeout
[HPM] Error occurred while trying to proxy request /api/game/leaderboard from localhost:3000 to http://localhost:5000 (ENOTFOUND) (https://nodejs.org/api/errors.html#errors_common_system_errors)
I'm using the setupProxy.js as follows:
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = app => {
console.log('from setupPrxoy.js');
app.use(
'/api/**',
createProxyMiddleware({
target: 'http://localhost:5000',
changeOrigin: true,
})
);
};
That seems to be working fine as I get the following when I start the React dev server:
[HPM] Proxy created: / -> http://localhost:5000
This is my server app.js:
const express = require('express');
const cors = require('cors');
const PORT = process.env.PORT || 5000;
const app = express();
const corsOptions = {
credentials: true,
};
app.use(cors(corsOptions));
app.use(express.json())
app.use(express.urlencoded({extended: true}))
//ROUTES
require('./routes/currentGame')(app);
app.listen(PORT, () => {
console.log(`Server started on ${PORT}`);
});
And that routes file:
const db = require('../models');
module.exports = app => {
app.get('/api/game/leaderboard', async (req, res, next) => {
try {
await db.Entry.find({
gameNumber: 2
})
.limit(50)
.populate('user', 'username')
.sort({ totalScore: 'descending' })
.exec((err, entries) => {
if (err) {
return next(err);
} else {
const leaderboard = [];
entries.forEach(entry => {
let newObj = {
totalScore: entry.totalScore,
username: entry.user.username
};
leaderboard.push(newObj);
});
return res.status(200).json(leaderboard);
}
});
} catch (err) {
return next(err);
}
});
}
The API works fine in the client, it returns the JSON as expected.
I've tried rolling back to older versions of React, React-Dom, React-Scripts and HPM but no luck.
I've tried removing the HPM and using a simple proxy in the package.json on the client side. Didn't work, got a similar message.
So I know the proxy is working (I think)
I've looked up ENOTFOUND and worked out it is some sort of DNS Address Error.
This is what I get when I in the command line
node 5033 [mynamewithheld] 23u IPv4 0x93d5c87aa7d4fbd3 0t0 TCP *:3000 (LISTEN)
node 5035 [mynamewithheld] 23u IPv6 0x93d5c87aa770a0ab 0t0 TCP *:5000 (LISTEN)
I'm wondering if I need to do something with the Header Requests on the server or if the Ports are running differently?
Any help appreciated!!

I think I have narrowed the issue down to hardware.
It doesnt work on 2011 iMac running OS Sierra 10.12.6 which was I was using but tested on 2015 MacBook Air running OS Mojave 10.14.16 and it works.
Beyond knowing that is the issue, any idea how to fix so it works on the iMac?

Make sure localhost is mapped to 127.0.0.1 in your etc/hosts file.

Related

http-proxy module doesn't work with create-react-app, but works with serve -s build

http-proxy module doesn't work with create-react-app, but works with serve -s build
This is my proxy-server code.
So what it does - it joins 2 api servers on different ports and frontend to a single 80 port. When you open localhost:80/* it should open react frontend (3000 port). When you open /api it gives you data from 4000 port and /secondapi from 1000 port.
My 2 backend api servers are opening completely fine with it.
Also when I start frontend server using serve module it also works fine and returns my frontend part.
But if I start frontend at the same 3000 port using "npm start" my proxy server returns connect ECONNREFUSED ::1:3000
const httpProxy = require('http-proxy');
const http = require('http');
const { maintenanceHtml } = require('./maintenanceHtml');
const proxy = httpProxy.createServer();
const guiUrl = 'http://localhost:3000'; // react frontend app
const apiUrl = 'http://localhost:4000'; // 1st api server
const apiPrefix = '/api';
const fnApiUrl = 'http://localhost:1000'; // 2nd api server
const fnApiPrefix = '/secondapi';
const port = 80;
http.createServer((req, res) => {
let target = guiUrl;
if (req.url.startsWith(apiPrefix)) {
req.url = req.url.replace(apiPrefix, '/');
target = apiUrl;
}
if (req.url.startsWith(fnApiPrefix)) {
req.url = req.url.replace(fnApiPrefix, '/');
target = fnApiUrl;
}
proxy.web(req, res, { target })
proxy.on('error', (error) => {
console.log(error.message)
res.end(maintenanceHtml);
})
}).listen(port, () => {
console.log(`Proxy server has started on port 80`)
});
I think that there is react server settings that I'm not able to find.
There is a little example that you're able to start at your own PC.
https://github.com/b2b-Alexander/react-js-problem
Found solution on github: https://github.com/vitejs/vite/discussions/7620
I got installed new v18.12.1 version of NodeJS.
My main machine has v16.14.0
So I rolled back the version of NodeJS for my project.

"serve -s build" starts over my create-react-app "npm start" [duplicate]

http-proxy module doesn't work with create-react-app, but works with serve -s build
This is my proxy-server code.
So what it does - it joins 2 api servers on different ports and frontend to a single 80 port. When you open localhost:80/* it should open react frontend (3000 port). When you open /api it gives you data from 4000 port and /secondapi from 1000 port.
My 2 backend api servers are opening completely fine with it.
Also when I start frontend server using serve module it also works fine and returns my frontend part.
But if I start frontend at the same 3000 port using "npm start" my proxy server returns connect ECONNREFUSED ::1:3000
const httpProxy = require('http-proxy');
const http = require('http');
const { maintenanceHtml } = require('./maintenanceHtml');
const proxy = httpProxy.createServer();
const guiUrl = 'http://localhost:3000'; // react frontend app
const apiUrl = 'http://localhost:4000'; // 1st api server
const apiPrefix = '/api';
const fnApiUrl = 'http://localhost:1000'; // 2nd api server
const fnApiPrefix = '/secondapi';
const port = 80;
http.createServer((req, res) => {
let target = guiUrl;
if (req.url.startsWith(apiPrefix)) {
req.url = req.url.replace(apiPrefix, '/');
target = apiUrl;
}
if (req.url.startsWith(fnApiPrefix)) {
req.url = req.url.replace(fnApiPrefix, '/');
target = fnApiUrl;
}
proxy.web(req, res, { target })
proxy.on('error', (error) => {
console.log(error.message)
res.end(maintenanceHtml);
})
}).listen(port, () => {
console.log(`Proxy server has started on port 80`)
});
I think that there is react server settings that I'm not able to find.
There is a little example that you're able to start at your own PC.
https://github.com/b2b-Alexander/react-js-problem
Found solution on github: https://github.com/vitejs/vite/discussions/7620
I got installed new v18.12.1 version of NodeJS.
My main machine has v16.14.0
So I rolled back the version of NodeJS for my project.

Error occurred while proxying request localhost:3000/api/product to http://localhost:5000/

We are trying to create an simple eCommerce app using Typescript, express and nextjs.
When we make a request to it, it throws the following error.
[HPM] Error occurred while proxying request localhost:3000/api/product
to http://localhost:5000/ [ECONNREFUSED]
(https://nodejs.org/api/errors.html#errors_common_system_errors)
My friend is using Windows, and code is working on his PC but not on my Ubuntu desktop.
I tried killing the port like below. It also kills the port but this does not help.
$ sudo lsof -t -i:5000
6033
$sudo kill -9 6033
$sudo lsof -t -i:3000
6101
$sudo kill -9 6101
Proxy server is listening at server.js file as:
const express = require('express');
const next = require('next');
const { createProxyMiddleware } = require('http-proxy-middleware');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
app
.prepare()
.then(() => {
const server = express();
// apply proxy in dev mode
if (dev) {
server.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:5000',
changeOrigin: true,
})
);
}
server.all('*', (req, res) => {
return handle(req, res);
});
server.listen(3000, (err) => {
if (err) throw err;
console.log('> Ready on http://localhost:5000');
});
})
.catch((err) => {
console.log('Error', err);
});
Found the solution.
I have ignore node_module and upload folder in .gitignore
I forgot to add the folder after cloning. So, it was showing proxy error.
After I add upload folder error was resolved.

I have hosted my Loopback 4 application on iisnode windows web app, Getting the port from there as a pipe which Loopback 4 doesn't understand

I have hosted my loopback 4 application on iisnode windows web app, which is giving the port as pipe and in my loopback 4 application i am reading port as Process.env.PORT. And i am getting the error:
Cannot start the application. RangeError [ERR_SOCKET_BAD_PORT]: Port should be >= 0 and < 65536. Received \.\pipe\fde1f2c4-428f-5513-8114-c9520f1ba02d
I tried by manually giving port 80, 443 but that is not working and throwing error like
EADDRNOTAVAIL
Expected port to be a number but iisnode giving it as pipe, which loopback 4 is rejecting.
// index.js root file
const application = require('./dist');
module.exports = application;
// Run the application
const config = {
rest: {
port: (process.env.PORT|| 3000),
host: process.env.WEBSITE_HOSTNAME || "localhost",
openApiSpec: {
setServersFromRequest: true,
},
},
};
application.main(config).catch(err => {
console.error('Cannot start the application.', err);
process.exit(1);
});
// index.ts inside src
import {myApplication} from './application';
import {ApplicationConfig} from '#loopback/core';
export {myApplication};
export async function main(options: ApplicationConfig = {}) {
const app = new myApplication(options);
await app.boot();
await app.start();
const url = app.restServer.url;
console.log(`Server is running at ${url}`);
return app;
}
Please see our response in https://github.com/strongloop/loopback-next/issues/3507#issuecomment-518099844. Thanks.

How to troubleshoot problem with setting WebRTC server on vps?

I wrote a simple node express server for webRTC using peerjs-server and simple client using peerjs. Everything works fine on localhost, but when I try it on vps, I get error:
Firefox can't connect with server ws://my.vps/peerjs/peerjs?key=peerjs&id=hj3hpekwaa38fr00&token=ymtfvhagiw
PeerJS: Socket closed.
PeerJS: ERROR Error: Lost connection to server.
Error: "Lost connection to server."
emitError https://cdnjs.cloudflare.com/ajax/libs/peerjs/0.3.16/peer.min.js:1:16426
_initializeServerConnection https://cdnjs.cloudflare.com/ajax/libs/peerjs/0.3.16/peer.min.js:1:12260
emit https://cdnjs.cloudflare.com/ajax/libs/peerjs/0.3.16/peer.min.js:1:25516
onclose https://cdnjs.cloudflare.com/ajax/libs/peerjs/0.3.16/peer.min.js:1:19350
Server:
const express = require('express');
enter code here`const app = express();
const ExpressPeerServer = require('peer').ExpressPeerServer;
app.use(express.static('./public'));
const server = app.listen(80, () => { // 3000 on localhost
console.log('Express server listen on port ' + 80);
});
const options = { debug: true };
const peerserver = ExpressPeerServer(server, options);
app.use('/peerjs', peerserver);
app.use('/*', express.static('./public/index.html'));
Client:
var peer = new Peer('', {
host: location.hostname,
port: location.port || (location.protocol === 'https:' ? 443 : 80),
path: '/peerjs',
debug: 3
});
peer.on('open', function (id) {
console.log(id);
});
Any help appreciate.
It looks like you are connecting with server ws://my.vps/, which is a web socket to a server at http://my.vps/ which doesn't seem to exist.
It should probably also be using https (or wss)

Resources