Following is my code -
apps.js
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.get('/api/users', (_req, res) => {
res.send('Hello World');
})
app.listen(PORT, () => {
console.log(`Server running on port: `, PORT);
});
.env file
PORT=8000
Now when I run the program though terminal via command - node app.js
I am getting -
Server running on port: 3000
but I want it to run on 8000 and pick it from .env file. Let me know what I am doing wrong here.
I know while running from terminal I can define PORT=8000 or app.set() but I am looking to pick it from an environment file. Let me know what I am doing wrong here / in terms of understanding.
You can use dotenv npm package for custom environment variables.
Usage
Create a .env file in the root of your project:
PORT=8000
As early as possible in your application, import and configure dotenv:
require('dotenv').config();
// Your .env variables is now available in process.env object
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.get('/api/users', (_req, res) => {
res.send('Hello World');
})
app.listen(PORT, () => {
console.log(`Server running on port: `, PORT);
});
Read more in the official package: dotenv
Related
Yesterday, I had dotenv installed and referenced, and the Server was calling on port 4000 through env, I had Postman working and referencing the server but that stopped when I started my coding today, I have no idea what I changed, because I didn't think I had done anything.
My .env file is below:
PORT = 4000
NODE_ENV = DEVELOPMENT
DB_URI = mongodb+srv://<xxx>:<xxx>#products.<xxx>.mongodb.net/?retryWrites=true&w=majority`
My server.js file is below:
const app = require ('./app');
const connectDatabase = require('./config/database');
const dotenv = require ('dotenv')
//I'm switching between these two PORT constants to debug
const PORT = process.env.PORT
const PORT = 4000
const URI = process.env.URI
// environment variable setup (tutorial runs server through the root, hence the backend/...).
dotenv.config({ path: 'backend/config/config.env'});
// DB connection
connectDatabase();
app.listen(PORT, () => {
console.log(`Server running on PORT: ${PORT} as a ${process.env.NODE_ENV} project`);
});
When I run with the port number called directly through server.js the port loads as 4000:
But when I run through the environment variables I get undefined:
Not that it matters, but I turned off my VPN and restarted it. Not sure why it makes the error now.
On your server.js file, you are defining the PORT const using the process.env.PORT before calling dotenv.config(), because of that you env vars are not defined yet.
Try change your code to:
dotenv.config({ path: 'backend/config/config.env'});
const PORT = process.env.PORT || 4000;
const URI = process.env.URI;
I am trying to build my first app. It's a calculator that measures the level of caffeine in your blood.
I copied the code from : https://expressjs.com/en/starter/hello-world.html (copied below), but it is not showing a page with the words "Hello World!".
Instead, I see 2 links to my 2 files within my folder "CaffeineCalc" (calculator.js + json file). I have copied below the page it shows me. [what my browser page shows instead of Hello World][1]
const express = require('express');
const app = express();
const port = 5500;
app.get('/', (req, res) => {
res.send('Hello World!')
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
});
Let me know if you understand what I am doing wrong. Thanks!
[1]: https://i.stack.imgur.com/L6bnv.png
From The Picture you provide, it looks like a live-server running and not your NODE application
So To Fix That You Need to open the path of that dir in any terminal or command prompt and run
$ npm install
cause I can't see any node_module folder
then
$ node index.js
to start the node server
You can now open Your Browser to
http://localhost:5000
you need to use express urlencoded.
const express = require('express');
const {
urlencoded
} = require('express');
const app = express();
const PORT = process.env.PORT || 4000;
app.use(express.json())
app.use(urlencoded({
extended: true
}))
app.listen(PORT, () => {
console.log(`Example app listening at http://localhost:${PORT}`)
})
For some reason my express router is not processing requests correctly. My router module is in the same directory as the app entry point. The app is located in index.js:
const express = require('express')
const app = express()
// loading router
const mainRouter = require('./mainRoutes.js')
// mounting router
app.use('/', mainRouter)
app.listen(3000)
console.log('Express server running on port 3000')
The router module is located in mainRoutes.js:
const path = require('path')
const express = require('express')
const mainRouter = express.Router()
mainRouter.get('/', function (req, res) {
res.send('Hello World, I\'m Node.js')
})
mainRouter.get('/about', function (req, res) {
res.sendFile(path.join(__dirname, 'views', 'about.html'))
})
module.exports = mainRouter
When I launch the server locally with live-server and make the following example request in chrome browser:
http://127.0.0.1:8080/about
I get the following error response:
Cannot GET /about
Does anyone have any idea as to what the issue is?
The server is listening on port 3000: app.listen(3000)
But you're trying to access it from port 8080: http://127.0.0.1:8080/about
Try http://127.0.0.1:3000/about
I'm reading from a few other similar questions/answers and one point seems to be that any valid JS is basically TS as well?
If that is the case:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
TS attempt
import express = require('express');
import bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
const port: number;
port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
import express from "express";
import bodyParser from "body-parser";
import path from "path";
import config from "config";
const app = express();
app.use(bodyParser.json());
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
Although the above code can still be considered "valid javascript" i would say that is the idiomatic typescript way of writing the code snippet you posted. This is because typescript makes any module imported with require syntax of type any where-as import will always try and look for type definitions and complain if they're not there.
When working with Express/NodeJS/Typescript i would always suggest starting with this demo app as it is a really good boiler plate for getting started with those technologies and is maintained by microsoft.
https://github.com/microsoft/TypeScript-Node-Starter
I have a React app which I start from express server. I have public directiory with /public/index.html file and copy of that file in '/' directory.
Code:
const express = require('express')
const path = require('path')
const port = process.env.PORT || 8080
const app = express()
app.use(express.static(__dirname))
app.get('*', (req,res) => {
res.sendFile(path.resolve(__dirname, './public/index.html'))
})
app.listen(port)
console.log('Server started: '+ port)
My server.js file is in '/' directory.
Express opens index.html in '/' directory instead of one this one in public directory, any suggestions why ?
I think you need app.use(express.static(path.join(__dirname, '/public/')))
Your use statement handles get requests first and makes app.get(* obsolete.