How to fix Node express error: cannot GET - node.js

I'm trying to create a simple backend api for an app I'm working on (create-react-app) and decided to use node express. I'm getting the error 'cannot GET' when I open my browser and I don't understand why.
Here is my server/index.js file:
const express = require("express");
const PORT = process.env.PORT || 3001;
const app = express();
app.get("/api", (req, res) => {
res.json({ message: "Hello from server!" });
});
app.listen(PORT, () => {
console.log(`Server listening on ${PORT}`);
});
app.listen(PORT, () => {
console.log(`Server listening on ${PORT}`);
});
Here is my start script:
"scripts": {
"start": "node index.js"
}
In my console I see this error:
Failed to load resource: the server responded with a status of 404 (Not Found)
This is my folder structure:
I have an app called 1REPMAX that contains the folders
>build
>node-modules
>public
>server
>node_modules
>index.js
>package-lock.json
>package.json
>src
.gitignore
package-locj.json
package.json
So what I've been doing is I cd into server and then run npm start.
When I open my browser to localhost:3001 I get the error. Any help on what I'm doing wrong? If more information is needed just let me know. Also, when I ran npm start the first time it started up fine, but now every time I run it I get this error:
code: 'EADDRINUSE',
errno: -48,
syscall: 'listen',
address: '::',
port: 3001
I don't know if this has something to do with it or not.

The first error is caused because your app is not listening to the / path, only the /api path.
The second error is caused by a duplicate app.listen() call in your server/index.js file.
Your code should look something like this in order to resolve the issues:
const express = require("express");
const PORT = process.env.PORT || 3001;
const app = express();
app.get("/", (req, res) => res.send("Main page"));
app.get("/api", (req, res) => {
res.json({ message: "Hello from server!" });
});
app.listen(PORT, () => {
console.log(`Server listening on ${PORT}`);
});

Related

Openshift nodeJS successful deployment, but got "Application is not available"

I have created simplest nodeJS app and it running locally, but not on OpenShift.
I use Import from Git and the code imported and build successfully.
When I click Open URL in my app, it show "Application is not available" page.
index.js:
const express = require('express');
const http = require('http');
const app = express();
const server = http.createServer(app);
app.get('/', (req, res) => {
res.send('Hello from Node.js Starter Application!');
});
const PORT = process.env.PORT || 8000;
server.listen(PORT, () => {
console.log(`App started on PORT ${PORT}`);
});
package.json:
{
"scripts": {
"start": "node index.js",
},
"dependencies": {
"express": "^4.18.2",
}
}
The most last from logs:
> node index.js
App started on PORT 8000
What I have missed to successfully run my server on OpenShift?
Thank you

process.env.PORT and process.env.NODE_ENV are both returning undefined

I am trying to learn MERN and have hit an issue straight away
App.listen(process.env.PORT, () => {
console.log(`Server started on PORT: ${process.env.PORT} in ${process.env.NODE_ENV} mode.`)
})
returns "Server started on PORT: undefined in undefined mode."
Here is structure
backend:
config:
config.ev
App.js
server.js
App.js>
const express = require('express); const App = express(); module.exports = App
server.js> `const App = require('./App');
const dotenv = require('dotenv')
// Config set up
dotenv.config({ path: 'backend\config\config.env'})
App.listen(process.env.PORT, () => {
console.log(Server started on PORT: ${process.env.PORT} in ${process.env.NODE_ENV} mode.)
})`
config.env PORT = 4000 NODE_ENV = DEVELOPMENT
to require dotenv, use this instead of what you have currently
const dotenv = require("dotenv").config();
i also noticed some typos in your question like the missing quotation mark when you required express but i assume this was a typo from writing it on here and not in your actual code.
and you can find more info on dotenv here

conflicting port numbers in react

I have a React app where I specified the port number in server.js as
const port = process.argv[3] || 3500;
At the bottom of the same file I wrote:
app.listen(port, () => console.log(`Web service running on port ${port}`));
While the app is able to run in my browser, unfortunately in the console of my text editor it says Web service running on port 3500 even when the url says localhost:3000.
I know that React uses port 3000 as default... but don't know why the app chose to use port 3000 instead of the port 3500 that I specified above.
To try and fix this I tried to install the dev dependency cross-env and in my package.json "start" script I specified cross-env PORT=3500.
After that change, I see that my React app is now running in the browser on Port 3500... but I am unable to avoid the message from the server.js file that says "Web service running on the Port # that I specified in the server.js file".
In server.js when I use const port = process.argv[3] || 3500; in conjunction with the cross-env port 3500 change in package.json... I get the message "Something is already running on Port 3500". So it seems impossible to get the correct console message that the React app is really running properly in the browser on Port 3500.
Full Express server.js below:
const jsonServer = require("json-server");
const chokidar = require("chokidar");
const cors = require("cors");
const fileName = process.argv[2] || "./data.js";
const port = process.argv[3] || 3500;
let router = undefined;
const app = express();
const createServer = () => {
delete require.cache[require.resolve(fileName)];
setTimeout(() => {
router = jsonServer.router(fileName.endsWith(".js")
? require(fileName)() : fileName)
}, 100)
}
createServer();
app.use(cors());
app.use(jsonServer.bodyParser)
app.use("/api", (req, resp, next) => router(req, resp, next));
chokidar.watch(fileName).on("change", () => {
console.log("Reloading web service data...");
createServer()
console.log("Reloading web service data complete.");
});
app.listen(port, () => console.log(`Web service running on port ${port}`));```
Express Server:
you can run express server in the any port you want it to run
const port = process.env.port || 4000 //? can be any port number
the console log you are getting in the editor is from the server and not from the react app.
React App:
by default react app runs in port 3000 if you want to change the Port of the react app then use react-scripts like this
"start": "set PORT= <Your Desired Port> && react-scripts start"
or you can set port directly from terminal like this
PORT=4000 npm start //? or any other port number
app.listen is for express servers. To run a react server use react-scripts. To change port number use the PORT environment variable.

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.

Proxy Issue ENOTFOUND Create-React-App Http-Proxy-Middleware Express

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.

Resources