Setting up URL base for JSON with expressjs - json

I am completely new to node ExpressJS and am required to rewrite a rule for my server data source (jason format).
./
../public/
/public/css
/public/js
/public/index.html
../datasource/
/datasource/carmodel.json
The default static directories are set in:
app.use(express.static(__dirname + '/../public'));
The above work and everything runs under the 3000 port fine locally.
I need to rewrite the URL for my json file (datasource/carmodel.json) by replacing datasource with car/models/. However my application is unable to find the /datasource/carmodel.json file. I have attempted to recreate this via the following:
app.use('car/models/', require('./../datasource/'));
But I still cannot find the json source URL. It does not matter if I type: http://localhost:3000/car/models/carmodel.json or http://localhost:3000/datasource/carmodel.json for that matter. Is there something I am missing?
------------------
EDITED
------------------
Please see my project structure:
./
node_modules/
public/
css/
custom.css
js/
app.js (angular)
index.html
datasource/
carmodel.json
index.js (express file)
package.json
README
Currently my static folder is running of localhost:3000/. Contents of datasource/index.js:
var express = require('express');
var app = express();
app.use(express.static('public'));
//json
app.get('/car/models/:filename', function(req, res){
var filename = req.params.filename;
var fileDir = 'server/' + filename;
res.download(fileDir);
})
app.listen(3000, function(){
console.log('App started on port 3000!');
});

check something like this:
app.get('/car/models/:filename', function(req, res){
var filename = req.params.filename;
var fileDir = __dirname + '/datasource/' + filename;
res.download(fileDir);
})
then this http://localhost:3000/car/models/carmodel.json should work. I dont test it, youst write from head, therefore there may be some typos.
My solution is not safe. You shoud validate 'filename' before production use (all data from user must be validated).

Related

Express: serving static files in express using app.use() not working on * route

I am trying to serve static html and css files using express on any route. The files are present in public folder in the same directory the express file is present. The express code is given below:
const express = require('express')
const path = require('path')
const app = express()
// app.use('*', express.static('./public')); // Not Working
// app.use('/', express.static('./public')); // Working but only limited to home route
app.use(express.static('./public')); // Working but only limited to home route
app.listen(5000, () => {
console.log('server is listening on port 5000....')
})
if the folder public in the same root with your node app use:
app.use(express.static('public'))
To create a virtual path prefix (where the path does not actually exist in the file system) for files that are served by the express.static function, specify a mount path for the static directory, as shown below:
app.use('/static', express.static('public'))
Now, you can load the files that are in the public directory from the /static path prefix.
http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
However, the path that you provide to the express.static function is relative to the directory from where you launch your node process. If you run the express app from another directory, it’s safer to use the absolute path of the directory that you want to serve:
const path = require('path')
app.use('/static', express.static(path.join(__dirname, 'public')))

nodejs sendfile html page

I have this code that allows me to open a HTML page from specific folder, if I use server.js to open that HTMLpage so the page it is generating with all the css and jquery files but if I try to move the get statement to the routes folder then the page is generated but without any css and jquery files and I don't know why !
what I did in the server.js for the generation of the HTML page is below which is working perfectly :
const folderPath = __dirname + '/public/AppTemplate/src'
app.use(express.static(folderPath))
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname + '/public/AppTemplate/src/index.html'));
});
but what I'm trying now is to get the html page from routes.js :
step 1 :
I implemented this statement in server.js
app.use('/users', require('./backend/routes/profile.routes.js'));
step2 :I tried this statement in routes.js with simple modification :D :
router.get('/profile', function (req, res) {
const dirname = __dirname;
console.log(dirname)
const newpath = dirname.length - 14;
const newP = dirname.substring(newpath, dirname.lastIndexOf("/"));
console.log(newP);
res.sendFile(path.join(newP+ '/public/AppTemplate/src/02-ProfilePage.html'));
});
the step 2 is working but I couldn't get all the associated files (jquery css ...) which are located in
/public/AppTemplate/src
the image of the output is below :
hope I mentioned everything,
Best Regards,
It's because of the content in the 02-ProfilePage.html has an incorrect path.
Check the path in the script tags. If there is a slash it means that it's already in the /public/AppTemplate/src which you specified.
For example, /js/file.js will actually point to /public/AppTemplate/src/js/file.js
Perhaps try adding a / in front of your path in the script tag.
Example:
/css/x/y/z/ instead of css/x/y/z
You will have to append a / to all the routes in your script/link tag to be able to successfully load the local resources.
You can use the find and replace functionality in your code editor or IDE to speed up the process if possible.

Failed to load resource: the server responded with a status of 404 (Not Found) issue in Nodejs app

I need help. I looked up the solutions here but still couldn't find it. So I'm practicing something in Goorm ide and I have come to a dead-end. I am trying to link main.js(which is in js folder) file by putting the script in the footer. But I'm getting an error which says
Failed to load resource: the server responded with a status of 404 (Not Found)
I also uploaded some png files in lib folder and I'm getting the same error after trying to access those in an ejs template.
Root folder consists of js, lib and views folder and some others which are not relevant.
To link the main.js in footer.ejs(which is in partials folder inside views), I used
<script type="text/javascript" src="../../js/main.js"></script>.
The png images which are uploaded in lib/images folder, I tried to access those from an ejs template in views so I used
<img src="../lib/images/image1.png">.
I am getting that error in both the cases. It would be highly appreciated if someone could help. This is how my root folder looks like -
EDITED:
This is the app.js code:
require('dotenv').config();
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var indexRoute = require("./routes/index");
var flash = require("connect-flash-plus");
var session = require('express-session');
// APP CONFIG
app.use(express.static(__dirname + "/public"));
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({extended:true}));
app.set('json spaces', 2);
app.use(session({
secret: 'boom',
cookie: { maxAge: 60000 },
saveUninitialized: true,
resave: true
}));
app.use(flash());
app.use(function(req, res, next) {
res.locals.error = req.flash("error");
next();
});
// routes
app.use(indexRoute);
app.listen(3000, function(){
console.log("Server has started");
})
Your Express configuration specifies that all of your static files will be accessed from the public directory:
app.use(express.static(__dirname + "/public"));
This means that any files you want to access in your web browser must be within this directory (or a subdirectory of it).
For instance, if you want to access main.js, and it's location in public/main.js, you would access it on the frontend like this:
<script type="text/javascript" src="/main.js"></script>
Note that on the frontend, you must not include the public/ prefix.

Run Node.js by passing parameters

I have a server running with Node.js and my question is, whether it's possible when running the server like I usually do (with the command node app.js) to pass parameters (eg. [UserID; IterationID;ProfileID]). Later I want to use these parameters to generate canvas (which I'm not sure how to read the parameters).
var fs = require('fs');
const log=require('simple-node-logger').createSimpleLogger();
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
var port = process.env.PORT || 8000;
app.use(express.static(__dirname + '/server'));
app.use(express.static(__dirname + '/public'));
app.use('/images', express.static(__dirname +'/images'));
app.get('/', function(req, res){
res.sendfile('main.html');
});
app.listen(port, function(){
//console.log('server is running on ' + port);
});
app.post('/submit', function(req, res){
console.log(req.body.rank);
return res.sendfile('success.html');
});
Thank you very much in advance!
You can pass the environment parameters. Here is linux terminal command example:
YOUR_PARAM=param_value YOUR_PARAM2=param_value2 node app.js
Inside the code you can access those params inside process.env object:
console.log(process.env.YOUR_PARAM); // "param_value"
console.log(process.env.YOUR_PARAM2); // "param_value2"
This is usually done to define where application is running (local, development server, production server).
In my opinion it is the best to put the rest of the configuration in the JSON files and load them according to the application environment.
So basically first you define where your app is running and then based on that load the correct configurations from specified file. That way you can even share the configuration with the rest of the team over git.
P.S.
It is also worth mentioning that convention is to define process.env variables with capital letters in order to avoid overwriting some of the nodejs or system environment variables (if you console.log the process.env object you will see lot of configuration data in there).

Express routing returns undefined randomly

I am trying to learn Express with NodeJS and would like to render my views with plain HTML. I hacked together a webserver based on the Express API documentation and several Stack questions, particularly the answer by Andrew Homeyer in this question which states
You can have jade include a plain HTML page:
in views/index.jade
include plain.html in views/plain.html
... and app.js can still just render jade:
res.render(index)
My directory structure looks like this
Project
*web.js
Public
img
js
lib
gallerific
*jquery.opacityrollover.js
*jquery.gallerific.js
angular
theme
views
partials
*index.html
*index.jade
and my server looks like this.
var express = require('express'),
jade = require('jade');
var app = module.exports = express();
app.configure(function(){
app.set('views', __dirname + '/public/views');
app.use("/public/lib", express.static(__dirname + "/public/lib"));
app.use(express.static(__dirname + '/public'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.set('view engine', 'jade')
app.use(express.bodyParser());
});
app.get('/', function(req, res) {
res.render('index');
});
app.get('/partials/:name', function(req, res){
var name = req.params.name;
res.render('/public/partials/' + name);
});
app.get('/public/data/:name', function(req, res){
var name = req.params.name;
res.json('/public/data/' + name)
});
app.listen(3000, function(){
console.log("Express app listening on port %d in %s mode", this.address().port, app.settings.env);
});
What I am seeing is that certain files fail to load from directories in which everything else loads just fine. For example, my Gallery page fails to load the jquery.gallerific.js javascript file from my lib/gallerific directory while it does load the jquery.opacityrollover.js. I have poked around with Chrome Developer Tools and see the following
I had this site working with the Angular Bootstrap webserver so it doesn't seem to be a javascript error with the client side code. Does anyone know what I might doing that would cause this problem?
The source is available at https://github.com/jamesamuir/express-simple-html.git
I figured it out. It turns out I had to resolve paths that I had forgotten about so that Express could render them correctly. It wasn't that the Gallerific javascript library didn't load, it was throwing an error on the image source of undefined for my gallery images (I am pulling them from a JSON file).
Once I put the appropriate paths in for the images and the data file, everything started working again. Thanks to everyone who provided a suggestion for me. It really helped me to work through the problem.