How launch an express Web Node.js from a batch file - node.js

I have an app.js script that contains an express node website
const express = require('express');
const app = express();
const path = require('path');
const router = express.Router();
const fs = require('fs');
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static('public'));
…
app.listen(3000, function () {
console.log('avalaible at http://localhost:3000');
});
until now I launch website by writing in cmd
node ./app.js
Then I go to adress http://localhost:3000 in my browser
I would have a batch or another way to those operations just by doucle click on a file
Could you help me please?

In the Node js project folder create a .bat file and put this on it:
node ./app.js
start "" http://localhost:3000
when you click the file this should launch your nodejs app and open your default browser on the given address.

Related

Serving Static file publically in nodejs :- Not Working

In my nodejs server file, I am trying to server static folder the code goes as below :-
server.js
const express = require("express");
const app = express();
require("dotenv").config();
const cookieParser = require("cookie-parser");
const bodyParser = require("body-parser");
const { connectDB } = require("./config/connectDB");
connectDB();
const upload = require("./routes/uploadsFile");
const user = require("./routes/user");
const path = require("path");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.json("content-type", "application/json"));
const publicFolder = path.join(__dirname, "../uploads");
console.log(publicFolder);
app.use(express.static(publicFolder));
app.use("/api/v1/upload", upload);
app.use("/api/v1/user", user);
const PORT = process.env.PORT || 3030;
app.listen(PORT, () => {
console.log(`Server Started Listening On PORT ${PORT}`);
});
The folder structures goes below :-
The same error I am getting as everyone
Cannot GET /uploads/image/actual-size/banner-Image-1.jpg
Can someone please help me. I have gone through many problem already answered like this on Stackoverflow, but unable to get the proper solution.
You defined uploads to be the root directory for serving static files which means the request paths must not start with /uploads. In your example above change the path to:
/image/actual-size/banner-Image-1.jpg
From the docs:
Express looks up the files relative to the static directory, so the
name of the static directory is not part of the URL.
I got the solution of the problem.
I was calling the GET URL by
localhost:${port}/uploads/image/actual-size/image.jpg
But I had to call like this because uploads folder is being server by default
localhost:${port}/image/actual-size/image.jpg

How to send css files with express js

I am having a hard time sending css files with express. The way my project is structured is I have a src folder and inside the src folder is the app.js for the express code as well as another folder titled "public". Inside of this public folder I have an experience.html page as well as an experience.css page. I can only get the html to render on the page and cannot get the css styling to show up. Attached is my code for the app.js page.
const express = require('express');
const app = express ();
const port = process.env.Port || 3000;
app.get('/experience', (req, res) => {
res.sendFile(__dirname+'/public/experience.html');
})
app.use(express.static('/public/experience.css'))
app.listen(port);
Just using middleware is enough, you don't need dedicated get routes to the files unless you want to mask some of the filenames.
This should work for your case
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.listen(3000);
You can access them on http://localhost:3000/experience.html, http://localhost:3000/experience.css
You can use the Express static middleware with the path to the public folder.
Once you do that, you can expose a route to the files (or) you can access at localhost:9900
//Import modules
const express = require("express");
const path = require("path");
// Define PORT for HTTP Server
const PORT = 9900;
// Initialize Express
const app = express();
app.use(express.static(path.join(__dirname, "public")));
app.listen(PORT, (err) => {
console.log(`Your dog server is up and running!`);
});

I have problems to run server.js in terminal

enter image description here[
// Setup empty JS object to act as endpoint for all routes
projectData = {};
// Require Express to run server and routes
const express = require('express');
const app = express();
// Start up an instance of app
const PORT = 8080;
app.listen(PORT, () => {
console.log('Hi');
console.log(`the port that we will use is ${port}`);
});
/* Middleware*/
//Here we are configuring express to use body-parser as middle-ware.
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Cors for cross origin allowance
app.use(cors());
// Initialize the main project folder
app.use(express.static('website'));
// Setup Server
app.post('/link', function(req,res) {
});
What should i do to run this in terminal
*I tried alot of solutions bot it's not working
in the terminal[
1.
it can not find the file
]3*
I think you need to install the 'body-parser' library and send it to call in your file
npm install body-parser
const bodyParser = require('body-parser');
app.use(bodyParser.json());
You don't need to use bodyparser if you use latest or after 4.0 version of Express.js. You can use
app.use(express.json()) // Parse Json Bodies
app.use(express.urlencoded()); //Parse URL-encoded bodies
as middlewares instead, without any package. They will solve your problem.

Combine node.js rest api's and angular on same server

We first developed REST api's using node.js and have that running on a VPS. We now have developed an Angular web app to display data that comes in via a mobile app that calls some of the REST api's and then updates the data by calls back to other REST API's. Running the Angular app on the localhost was able to successfully call the REST api's.
We want to combine both applications on the same server. After searching around it seemed that we could add commands to the REST api server.js to pass urls that didn't meet the REST api path to Angular. Code snippet is below:
// API verison
var apiVersion = '/v1'
var fs ;
var https ;
// Dependencies
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
// MongoDB
...
// Express
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Routes
app.use(apiVersion, require('./routes/api'));
// Start server
fs = require('fs')
https = require('https')
https.createServer({
key: fs.readFileSync('...'),
cert: fs.readFileSync('...')
}, app)
.listen(443, function () {
console.log('HTTPS Server running on default port 443')
});
// Pass request to angular?
app.use(function(req, res) {
var path = require('path');
res.sendfile(path.resolve('/home/.../index.html')); // but not getting anything
});
The REST api's still work but when directing a browser to 'mydomain.net' I just get a blank page. I don't see any errors on the node/error logs.
Any ideas?
You can do something like this. Use static content to send from the dist folder and rest will work fine. I have added two reference in case you might need them to refer.
var apiVersion = '/v1'
const fs = require('fs')
const https = require('https');
const path = require('path')
// Dependencies
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
// MongoDB
...
// Express
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Pass request to angular?
app.use('path', express.static(path.resolve('your path should be correct')));
// Routes
app.use(apiVersion, require('./routes/api'));
// Start server
https.createServer({
key: fs.readFileSync('...'),
cert: fs.readFileSync('...')
}, app)
.listen(443, function () {
console.log('HTTPS Server running on default port 443')
});
Check here1 or here2 for more details, there are simple steps to follow.

npm run build cannot find index.html in public subfolder

I continue to get the error below when I try to build a production version of my app. Npm run build is looking for my index.html file in public, but it thinks my public folder is in my root directory whereas it is in the client subfolder.
Could not find a required file.
Name: index.html
Searched in: C:\Users\wharfchillin\wharf-chillin-app\public
My public folder is located in a sub-folder of my app:
client
--->public
------>index.html
I have tried to make this clear in my server.js file in numerous ways:
UPDATED
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const passport = require("passport");
const path = require('path');
const users = require("./routes/api/users");
const plaid = require("./routes/api/plaid");
const app = express();
const publicPath = path.resolve(__dirname);
// Bodyparser middleware
app.use(
bodyParser.urlencoded({
extended: false
})
);
app.use(bodyParser.json());
app.use(express.static(publicPath));
app.use('*', (req, res) => {
res.sendFile(path.resolve(publicPath));
});
// production mode
if(process.env.NODE_ENV === 'production')
app.use(express.static(path.resolve(publicPath)));
console.log('test')
console.log(publicPath)
Any advice would be more than appreciated.
You are using window os, window os's path use backward slash, but in your node app, you are define the path using forward slash, node has api to handle this, path.resolve. Stop using path.join

Resources