How to serve a specific file node server - node.js

Let us say I have a directory with 2 files: c:\file1\index.html and c:\file1\test.html. I am trying to start a server with node js on a specific port. Now I used app.use('/', express.static(path.join(__dirname))) as the directory to serve the file. My question is how can I make it serve c:\\file1\test.html with the code I have right now it serves c:\\file1\index.html? Thanks in advance.
const express = require('express')
const app = express()
const path = require('path')
//loads index.html
app.use('/', express.static(path.join(__dirname)))
app.listen(3000, () => console.log('Server up on port 3000'))

Would this work for you?
const express = require('express')
const app = express()
//specify public folder
app.use(express.static('file1'));
app.listen(3000, () => console.log('Server up on port 3000'));

Related

Run multiple executables of same application on different ports in NodeJS express framework with dotenv

I am having a NodeJS application with some basic routes and sql server connectivity. I am using pkg for the executables. All the configuration settings are stored on .env file. When I am trying to run multiple instance of the application from different directories with different port number specified in the .env file, my app is crashing with "EADDRINUSE" error code and says the particular port is used. I am able to run only single instance of application with any defined port number in .env file. I didn't explicitly use any default port number in the application.
"use strict";
const express = require("express");
const mac = require("./auth/auth");
const ejs = require("ejs");
var log = require('./utils/scroll');
var bodyParser = require("body-parser");
const app = express();
app.use(require('./utils/init'));
app.use(bodyParser.urlencoded({ extended: true, limit: "500mb"}));
app.use(bodyParser.json({limit: "500mb"}));
app.use(require('./utils/cors'));
app.use('/',require('./routes'));
console.log(mac);
var port = (process.env.port);
log();
app.use("/", express.static("assets"));
app.set("view engine", "ejs");
app.listen(port,()=>{
console.log("Server Running at Port :", port);
});
Is there any other setting I have to do?.
I had tried configuring different .env files with different port numbers per application.
The port your express app will be using is the one defined by process.env.port which I assume comes for your .env file.
You need handle the case the port is already in use to automatically change the port number and try again.
Something like that:
const express = require("express");
const app = express();
app.portNumber = 3000;
function listen(port) {
app.portNumber = port;
app.listen(port, () => {
console.log("server is running on port :" + app.portNumber);
}).on('error', (err) => {
if(err.code === 'EADDRINUSE') {
console.log(`----- Port ${port} is busy, trying with port ${port + 1} -----`);
listen(port + 1)
} else {
throw err;
}
});
}
listen(app.portNumber);
Check this post for a more complete answer: https://stackoverflow.com/a/53110778/5103610

Calls to local host not working with ReactJS/Axios/Express

I am trying to build a full stack app using ReactJS for the frontend and ExpressJS for the backend. I use Axios to make calls from my frontend to my backend. When I make those calls, I get these errors:
My express index file:
const express = require('express')
const path = require('path')
var app = express()
const PORT = process.env.PORT || 5000
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`)
})
app.use(express.static(path.join(__dirname, "public")))
My get call from React frontend:
componentDidMount() {
axios.get("http://localhost:5000/servers.json").then((res => {
this.setState({ servers: res.data })
}))
}
React server is running on port 3000 and Express server is running port 5000, so there shouldn't be a conflict there...
The reason you are getting the error http://localhost:3000 is not allowed by Access-Control-Allow-Origin is because of the same origin policy, a security feature that's restricting your react script from accessing/communicating your server since they are from different origins. Please note that for documents or scripts to be considered as having the same origin they need to have the same protocol (e.g http / https), hostname (e.g localhost / www.my-server.com) and port. In your case port the react script runs at port 3000 while the express script is running on port 5000, thus the error.
To solve this, you need to enable CORS - Cross Origin Resource Sharing on your server side code. First install the cors dependency using the command
npm install cors
Then update the code in your server to look as follows:
const express = require('express')
const path = require('path')
const cors = require('cors')
const app = express()
app.use(cors())
const PORT = process.env.PORT || 5000
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`)
})
app.use(express.static(path.join(__dirname, "public")))
Hopefully this works for you.
This looks like a basic cors issue. Add this cors middleware to your express server. It's the state of the art solution to this problem.
const express = require('express')
const path = require('path')
var cors = require('cors')
var app = express()
app.use(cors())
const PORT = process.env.PORT || 5000
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`)
})
app.use(express.static(path.join(__dirname, "public")))
If you are interested about cors in general, check out the wikipedia page.

Running Swagger JSON through Swagger UI via node

I have done npm install swagger-ui-express in the root folder of the project and kept a swagger.json as well there. My app.js contains:
var swaggerUi = require('swagger-ui-express'),
swaggerDocument = require('./swagger.json');
const express = require('express');
const app = express();
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
// app.use('/api/v1', router);
const server = app.listen(3000, function () {
let host = "localhost"
let port = 3000
console.log("App listening at http://%s:%s", host, port)
})
I have created a folder api-docs as well inside the root project folder. When I run in terminal node app.js and see in the browser localhost:3000, it displays
Cannot GET /
What can be the issue?

Express launching Angular application

I have an express server setup online which loads multiple ports and those ports are setup on subdomains for example. port 9000 loads the main domain.com port 8000 loads the main application at "app.domain.com" port 1000 loads "signup.domain.com" and the build version of the app is on port 8500 "build.domain.com".
The application is an Angular application however when I go to load the Angular app it loads on port 4200 or it says 8500 is in use. So currently I am loading that in express like so:
// Build Application - In Development
var appbuild = express();
appbuild.get('/', function (req, res){
res.sendFile('/app/build/myapp/src/index.html', { root: '.' })
});
var port = 8500;
appbuild.listen(port);
console.log('Build App Listening on port', port);
So my question is in Express how can I instead of writing sendfile command make it launch the angular app in that location on port 8500 so my subdomain names will work. The reason I'm asking this is because right now all it does is load the index file but angular or the app isn't running so i just see source code that says app-root and a blank white page.
Thank you in advance.
Robert
--- Update. I've decided to post the entire Express file. My issue is trying to load a angular app on port 8500 from the subfolder upon booting of express. Here is the full server.js code:
// server.js
const express = require('express'),
path = require('path'),
bodyParser = require('body-parser'),
cors = require('cors'),
mongoose = require('mongoose'),
config = require('../config/DB');
mongoose.Promise = global.Promise;
mongoose.connect(config.DB).then(
() => {console.log('Database is connected') },
err => { console.log('Can not connect to the database'+ err)}
);
// Main Website
var web = express();
web.get('/', function (req, res){
res.sendFile('/web/index.html', { root: '.' })
});
var port = 9000;
web.listen(port);
console.log('Web Listening on port', port);
// Main Application
var app = express();
app.get('/', function (req, res){
res.sendFile('/app/index.html', { root: '.' })
});
var port = 8000;
app.listen(port);
console.log('Main App Listening on port', port);
// Build Application - In Development
var appbuild = express();
appbuild.get('/', function (req, res){
res.sendFile('/app/build/myapp/src/index.html', { root: '.' })
});
var port = 8500;
appbuild.listen(port);
console.log('Build App Listening on port', port);
// Sign up Portal
var sign = express();
sign.get('/', function (req, res){
res.sendFile('/signup/index.html', { root: '.' })
});
var port = 10000;
sign.listen(port);
console.log('Sign Up Portal Listening on port', port);
Refer to this link https://malcoded.com/posts/angular-backend-express
Update your code to the following:
const express = require('express');
const app = express();
app.listen(8500, () => {
console.log('Server started!');
});
You need to build the angular app if your angular version not 1.x
ng build
Also, I think this question is similar to your question:
Not able to view Angular app via express/heroku?

Express.js showing ERR_CONNECTION_REFUSED

I have installed node(v4.1.2) and express(4.13.3)
Node Server code:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
After running the node file and upon calling http://localhost:3000/ gives me ERR_CONNECTION_REFUSED.
Have you run in powershell at server directory?
node app.js
You are listening on port 3000.
So Try http://localhost:3000
At first install Node.js body parsing middleware.
Installation: npm install body-parser
Then add the following lines:
var bodyParser = require('body-parser');
app.use(bodyParser.json());
I think your problem will be solved. For more details, visit -
http://expressjs.com/en/resources/middleware/body-parser.html

Resources