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.
Related
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.
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.
I am new to node.js coding. I am learning to build a app I want to host on GCP App engine.
I have created a Node.js code which has hard requirement to listen to port 3000.
const dotenv = require('dotenv').config();
const express = require('express');
const app = express();
const crypto = require('crypto');
const cookie = require('cookie');
const nonce = require('nonce')();
const querystring = require('querystring');
const request = require('request-promise');
const { Console } = require('console');
// const PORT = process.env.PORT || 3000;
const PORT = 3000;
app.get('/', (req, res) => {
res.send('Hello App Engine!');
});
On Yaml file I have specifically added ports to forward.
network:
forwarded_ports:
- 3000/tcp
unless I dont use 8080 port, app engine is failing with 502 Bad Gateway.
Is there a way I can use Port 3000 in App engine.
It works if I change the Port to 8080. But I want this to be at 3000.
I created firewall rules
enter image description here
Nope, you cannot change the default port in GAE.
The forwarded_ports is intended to open access to other services listening on other ports but always there should be something listening on the port 8080.
You can create a dummy service listening in port 8080 and possibly redirect to your app in port 3000. Something else to keep in mind is that when accessing the desired service in port 3000 or any other, this should be specified in the url like https://PROJECT_ID.REGION_ID.r.appspot.com:3000 or more general https://PROJECT_ID.REGION_ID.r.appspot.com:PORT
So yesterday I was creating a DockerFile and I noticed that the port we were exposing was 8080 and I understand that Node Web Apps run on 8080. Why 8080??? Can't we use 3000 or 3001? Is it something with Docker or with Node?
const express = require('express');
// Constants
const PORT = 8080;
const HOST = '0.0.0.0';
// App
const app = express();
app.get('/', (req, res) => {
res.send('Hello World');
});
app.listen(PORT, HOST);
You can expose any port or set of ports using EXPOSE in Dockerfile.
EXPOSE 8080 3000 3001
Generally, the Node application uses default port as 3000. But you can change it with configurations.
I am using gulp-nodemon because of its most obvious of utilities.
Nodemon is a utility that will monitor for any changes
in your source and automatically restart your server.
But I am not understanding a practice which seems to be prevalent in express/node development.
I just started working with node and express but from what I understand:
app.js
var express = require('express'),
app = express(),
port = process.env.PORT || 8016;
app.get('/', function rootHndlr(req, res) {
/* body... */
res.send('welcome to my API!');
});
app.listen(port, function listenHndlr(){
console.log('Gulp is running my app on PORT ' + port);
});
The following is setting in the port to 8016 if not set.
port = process.env.PORT || 8016;
So now we binds and listens for connections on the specified host and port.
But then I see people configure in their gulp tasks the following to nodemon in their gulpfile.js
gulpfile.js
var gulp = require('gulp'),
nodemon = require('gulp-nodemon');
gulp.task('default', function() {
// content
nodemon({
script: 'app.js',
ext: 'js'
env: {
PORT: 8000
},
ignore: ['./node_modules/**']
}).
on('restart', function(){
consile.log('Restarting');
});
});
As you can one of the values in nodemon env: {PORT: 8000} Why set the port again?
Thanks!
People are using something like that as a fallback: port = process.env.PORT || 8016;
Your application should be flexible enough and by passing an env var to make it listen to another port. In general, this is the purpose of the env vars.
About your example, I suppose that there is a reason that the guy that wrote this gulpfile would like to make the app listen to port 8000. I would say that it is safe to change the value or to remove the PORT: 8000 as soon as you are 100% sure that there is no reason that the application needs to run on port 8000 (for example, it is behind a reverse proxy that forwards the traffic to port 8000).