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!!