express.js to GET json file in terminal - javascript

How do I GET a JSON file with express.js? I want to be able to access it in my Mac terminal. I'm working on a college assignment that asks me to write an HTTP server that will act as a simple data store. It must respond to GET, PUT, POST, and DELETE requests. I must use express.js instead of fs for this app.
So far, in my root directory I have a server.js file and I have a subdirectory called lib that holds another subdirectory called notes. Notes is where the JSON files will live.
In my root directory, I have a server.js file. This is all I have so far:
'use strict'
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var notes = './lib/notes';
app.use(bodyParser.json());
app.get('/', function(req, res) {
//
//this is the part I need help with
//
}
var port = process.env.PORT || 3000;
app.listen(port, function() {
console.log('Server started on port ' + port;
});
Once I have this GET request working, from my Mac terminal I should be able to send a GET request and receive all JSON files inside the notes directory.

...from my Mac terminal I should be able to send a GET request and
receive all JSON files inside the notes directory.
Provided you do not want to use fs module(well you dont need one either),
you can simply set a route for GET requests and send the json file in response with app.sendFile()
app.get('/',function(req,res){
res.sendFile(path.normalize(__dirname + '/foo.json'))
//assuming your app.js and json file are at same level.
//You may change this to 'lib/notes/foo.json' to fit you case
})
path is a module that you would need to require().
__dirname is the directory that the currently executing script is in.
and finally foo.json is the file containing your json
{
"name":"nalin",
"origin":"stackoverflow"
}
Here's the complete code for app.js
var express = require('express');
var path = require('path');
var app = express();
app.get('/',function(req,res){
res.sendFile(path.normalize(__dirname + '/foo.json'))
})
app.listen(3000);
Which will help you run the node server with node app.js.
Finally you can access the json with by
visiting http://localhost:3000/ on your browser
by running curl command on your mac terminal curl localhost:3000
Hope this helps.

You can serve your .json files as static:
app.use('/notes', express.static( notes ));
http://expressjs.com/starter/static-files.html
Or you can do it manually width path pattern:
app.get('/notes/:file', function(req, res) {
fs.readFile(notes + "/" + req.params.file, function(err, data) {
if(err) {
res.status(404).send('Not found');
} else {
res.contentType(req.params.file);
res.send(data);
}
res.end();
});
});

Related

Express server don't search static files in Angular 12 app

Background
I am migrating an Angular app in GKE cluster. The base docker image that I must use(company policy) does not have any options to install any new softwares like shell, Angular cli command ng etc. The base docker image has only Node installed.
There is a shared base url, let's say, www.my-company.com, that everyone has to use for app deployment with a path added after the base url like www.my-company.com/my-angular-app/ - all the other Angular apps must be differentiated using the path of the app.
What I did
Since I can't run ng serve command in the base image, I added Express dependency in the package.json in Angular application and created an express server to route the traffic to Angular app.
I was following this youtube video to configure the application - https://www.youtube.com/watch?v=sTbQphoYbK0&t=303s. The problem I am facing is to how I load the the static files in the application.
If I define absolute path inside sendFile method of server.js file, although the application is working, but in future, if I need to add any other files in the application, I have to create another route in server.js file.
I don't know how Express can search a file automatically from the static folder(and sub folders) and return only that file when needed. I defined a static folder too, but seems like it is not working.
Following is my server.js code
==============================
const express = require('express');
const http = require('http');
const path = require('path');
const port = 8080;
const contextPath = '/my-angular-app';
const router = express.Router();
const app = express();
app.use(contextPath, router);
app.listen(port, ()=> {
console.log("Listening on port: ", port);
});
app.use(express.static(__dirname + '/dist/testapp/'));
router.get('/', function(req, res) {
// to get index.html file
res.sendFile(path.resolve(__dirname + '/dist/testapp/index.html'));
});
router.get('/*', function(req, res) {
let path = __dirname +'/dist/testapp/' + req.path
console.log('full path: ', path);
// To return static files based on incoming request, I am facing problem here(I think)
res.sendFile(path);
});
==============================
I want Express will send any files based on file name in the request. It should also take care of nested directories in the /dist/testapp/ directory
/dist/testapp/ -> This is the directory where Angular generates code for my app after I execute ng build command
WEBAPP.get("/admin/script.js", (req, res) => {
console.log(req.path);
if (req.session.username !== "Admin") return res.render("error");
res.sendFile(__dirname + "/admin/admin.js")
});
WEBAPP.get("/admin", (req, res) => {
if (!req.session.loggedin) return res.render("error");
if (req.session.username !== "Admin") return res.render("error",);
res.render("admin", {
csrfToken: req.csrfToken(),
title: "ADMIN PORTAL",
username: req.session.username,
nav_avatar: GetImageURL(req.session.avatar, "small")
});
});
There's no need to publically share /admin/script.js in my case but if a user requests this URL say example.com/admin/script.js a check for username equaling "Admin" if all is okay we sendFile.
I would maybe assume that you're not properly targeting your static files. Perhaps console.log the target.

How to send headers in Express [MEAN]

I'm a beginner in Express. So I might've failed to frame the question properly. I have created a MEAN application wherein I've separated my frontend and backened. Frontend runs on port:4200 and server runs on port:3000. I wanted to run both frontend and backend on same port as part of deployment. I'm getting MIME type errors, someone told me that there is some problem with my server environment. Maybe I'm not sending headers properly. Here is my code:
I have mentioned tried solutions in the code itself as <----TRIED THIS
server.js
const express = require('express');
express.static.mime.define({'application/javascript': ['js']}); <----TRIED THIS
const bodyParser = require('body-parser');
const path = require('path');
// express.static.mime.define({'application/javascript': ['js']}); <----TRIED THIS
const api = require('./routes/api');
const PORT = 3000;
const app = express();
app.use(express.static(path.join(__dirname, 'dist')));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/api', api);
app.get('/', function(req, res) {
// res.send('Hello from the server'); <----TRIED THIS
// res.writeHead(200, {'Content-Type': 'text/html'}); <----TRIED THIS
// res.set('Content-Type', 'text/plain'); <----TRIED THIS
// res.setHeader("Content-Type","application/json"); <----TRIED THIS
res.sendFile(path.join(__dirname, 'dist/application/index.html'));
})
app.listen(PORT, function() {
console.log('Server listening on PORT '+PORT);
});
api.js
For instance I'm showing you GET function only
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const db = <my db string>;
const jwt = require('jsonwebtoken');
mongoose.connect(
...
)
function verifyToken(req, res, next) {
...
}
router.get('/myarticles', (req, res) => {
var person="Tanzeel Mirza";
console.log('Get request for tanzeel articles');
Article.find({contributor: person}, (error, article) => {
if(error) {
console.log(error)
}
else {
if(!article) {
res.status(401).send('Invalid email')
}
else if(2>4) {
console.log("test passed");
}
else {
res.json(article);
}
}
})
})
module.exports = router;
But still I'm getting
Loading module from “http://localhost:3000/runtime-xxx.js” was blocked because of a disallowed MIME type (“text/html”).
Loading module from “http://localhost:3000/polyfills-xxx.js” was blocked because of a disallowed MIME type (“text/html”).
Loading module from “http://localhost:3000/main-xxx.js” was blocked because of a disallowed MIME type (“text/html”).
Please correct me.
PS: I asked separate questions for MIME error here. But no answers.
Since your assets are inside dist/application folder, Use app.use(express.static(path.join(__dirname, 'dist/application')));
To match all web app routes, Use app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, 'dist/application/index.html'));
}).
This a generic route and will be called into action only if express can't find any other routes and always serve index.html. For example any valid /api route will never reach this handler, as there a specific route that handles it.
Final code for server.js
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const api = require('./routes/api');
const PORT = 3000;
const app = express();
app.use(express.static(path.join(__dirname, 'dist/application')));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/api', api);
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, 'dist/application/index.html'));
})
app.listen(PORT, function() {
console.log('Server listening on PORT '+PORT);
});
A few points to not.
To serve static files, you need not set any headers manually. Express looks up the files in the folder (dist folder in your case) you set as static directory with the express.static middleware function. Express also sets the response headers based on the file extension.
So you don't need express.static.mime.define in your code anymore.
In your case you have defined app.use(express.static(path.join(__dirname, 'dist'))); which listens for static files at dist folder. In this app.use command, you haven't used a mount path which means that all the requests will go through the static middleware. If the middleware finds an asset with the same name, path and extension in dist folder it returns the file, else the request is passed to the other route handlers.
Also, If you are using static middleware, as long as there is an index.html in dist folder (immediate child of dist folder), your route handler for "/" will never get invoked as the response will be served by the middleware.
If you don't have an index html file in dist folder(immediate child of dist), but it's present somewhere in subfolders of dist, and still you need to access it using root path "/", only then you need a route handler for path "/" as below.
app.get("/", function(req, res) {
res.sendFile(path.join(__dirname, "dist/application/index.html"));
});
JS files referred using "./" in dist/application/index.html are referred relative to dist folder itself and NOT dist/application folder.
You can refer this REPL for updated code 👉.
https://repl.it/repls/SoreFearlessNagware
Try below urls
/api/myarticles - Rendered by "/api" route handler
/api/myarticles.js - Rendered by static asset middleware because the file exists in dist/api folder
/ - rendered using "/" route handler and res.sendFile because index.html doesn't exist in dist folder.
/test.js - Rendered using static middleware because file exists in dist folder
Additional links for reference.
https://expressjs.com/en/api.html#res.sendFile
https://expressjs.com/en/starter/static-files.html
1.Build your angular project, either inside or outside the server folder using ng build cmd.
2.To build your project inside server, change the dist-folder path in angular-cli.
3.To change path, either use cli cmd or edit the angular-cli.json file's "outDir": "./location/toYour/dist"
Or by using this cli cmd ng build --output-path=dist/example/
4.Then In your server root file include the static build/dist folder using express.
5.Like this app.use(express.static(path.join( 'your path to static folder')));
6.Now restart your server.

Set Home Page in Express

I have some server side code in node js, which creates a express js object and runs the server. The app loads the index.html page which is inside the public folder. I have never written the code to serve the home page (mention below), still it works.
app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, 'public/index.html'));
});
I have not written this code so how does the index.html gets rendered. My understanding says express JS looks for the first instance of index.html page in all the static folders declared in the code and renders it, in my case the static folder is "publimc" and it has index.html at the root level.
server code follows below, which I have written.
var express = require('express');
var app = express();
var mongojs = require('mongojs');
var db = mongojs('contactlist', ['contactlist']);
var bodyParser = require('body-parser');
app.use(express.static(__dirname + '/publimc'));
app.use(bodyParser.json());
app.get('/contactlist', function (req, res) {
console.log('I received a GET request');
db.contactlist.find(function (err, docs) {
console.log(docs);
res.json(docs);
});
});
app.listen(8000);
console.log("Server running on port 8000");
The home page is rendered as part of the express.static middleware default options.
To disable this logic, set express.static(..., { index: false }).
If you want to change the file served as a home page, set express.static(..., { index: 'yourfile.html' }).
What this option does, in fact, is attempt to serve an index page with given file name for each directory in your public folder, so if you have public/foo/index.html then it will get served when requesting /foo/ path.

node how can My app find index.js

Folder structure
bin - www.js
lib - jsFiles...
models - jsFiles...
node_modules -Folders and Files
public - index.html
route - jsFiles...
index.js
package.json
I use Express, angular.js. Server starts at www.js and It calls
index.js. After that, When I type merely "localhost:3000" It shows me
public/index.html. I don't have route for '/' but It shows me
'public/index.html'. I can not understand this. Please let me know
about the process.
www.js
var debug = require('debug')('example-server');
var app = require(process.cwd()+'/index');
//listen at 3000 port
app.set('port',process.env.PORT || 3000);
var server = app.listen(app.get('port'),function()
{
debug('Express server listening on port ' + server.address().port);
});
index.js
var favicon = require('serve-favicon');
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
//Connection for DB
require('./lib/connection');
var employees = require('./routes/employees');
var teams = require('./routes/teams');
var app = express();
// Writing at routing table
app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended:true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname,'public')));
app.use(employees);
app.use(teams);
// send 404 to errorhandler
app.use(function(err,req,res,next)
{
var err = new Error('Not Found');
err.status = 404;
console.log(error);
next(error);
});
...
...
module.exports = app;
In express.js the sequence in which you register your middleware makes a huge difference.
When express.js receives a request, it starts from top and executes registered middleware.
Middlewares are registered in express app using app.use(middleware_goes_here) this type of middleware gets executed no matter what the request url is on the other hand you can also register a middleware like app.use('/url/path',middleware_goes_here) in this case we are registering this middleware to '/url/path' so this middleware will only get executed when you visit '/url/path' (and non of the previous matching middleware serves the request without calling next() )
This app.use(express.static(path.join(__dirname,'public'))); line of code does the magic.
You can go here (express.static ref) to know more about static content serving and routing.
Basically what happens is, we are configuring express.static middleware to serve static content "as is" from "public" folder. So when you make any request and it matches a static content in public folder, then it will serve it otherwise express.static will call next middleware in sequence.
So in your case, the first middleware that actually server input request is express.static without any route filters, so it servers index.html even without a specifically defined route. If your public folder had file at public/javascript/jquery.js then following url will map to it http://localhost:3000/javascript/jquery.js
NOTE: You do not have to specify "public" in the url, the way in which express.static is registered, it will server contents FROM "public" folder.
................
UPDATE: How does default work in express.static?
By default, app.use(express.static(path.join(__dirname,'public'))); this will take index.html as default document. If you want to set index2.html as your default document, you can do that by doing something like this app.use(express.static(path.join(__dirname,'public'),{index: 'index2.html'}));
Hope it helps.
Put a relative path to folder(one up in hierarchy).
var app = require('../index');

Basic webserver with node.js and express for serving html file and assets

I'm making some frontend experiments and I'd like to have a very basic webserver to quickly start a project and serve the files (one index.html file + some css/js/img files). So I'm trying to make something with node.js and express, I played with both already, but I don't want to use a render engine this time since I'll have only a single static file, with this code I get the html file but not the assets (error 404):
var express = require('express'),
app = express.createServer();
app.configure(function(){
app.use(express.static(__dirname + '/static'));
});
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
app.listen(3000);
Is there a simple way to do it (in one file if possible) or Express requires the use of a view and render engine ?
I came across this because I have a similar situation. I don't need or like templates. Anything you put in the public/ directory under express gets served as static content (Just like Apache). So I placed my index.html there and used sendfile to handle requests with no file (eg: GET http://mysite/):
app.get('/', function(req,res) {
res.sendfile('public/index.html');
});
Following code worked for me.
var express = require('express'),
app = express(),
http = require('http'),
httpServer = http.Server(app);
app.use(express.static(__dirname + '/folder_containing_assets_OR_scripts'));
app.get('/', function(req, res) {
res.sendfile(__dirname + '/index.html');
});
app.listen(3000);
this loads page with assets
You could use a solution like this in node.js (link no longer works), as I've blogged about before.
The summarise, install connect with npm install connect.
Then paste this code into a file called server.js in the same folder as your HTML/CSS/JS files.
var util = require('util'),
connect = require('connect'),
port = 1337;
connect.createServer(connect.static(__dirname)).listen(port);
util.puts('Listening on ' + port + '...');
util.puts('Press Ctrl + C to stop.');
Now navigate to that folder in your terminal and run node server.js, this will give you a temporary web server at http://localhost:1337
Thank you to original posters, but their answers are a bit outdated now. It's very, very simple to do. A basic setup looks like this:
const express = require("express");
const app = express();
const dir = `${__dirname}/public/`;
app.get("/", (req, res) => {
res.sendFile(dir + "index.html");
});
app.get("/contact", (req, res) => {
res.sendFile(dir + "contact.html");
});
// Serve a 404 page on all other accessed routes, or redirect to specific page
app.get("*", (req, res) => {
// res.sendFile(dir + "404.html");
// res.redirect("/");
});
app.listen(3000);
The above example is if you want to serve individual HTML files. If you were serving a single page JS app, this would work.
const express = require("express");
const app = express();
const dir = `${__dirname}/public/`;
app.get("*", (req, res) => {
res.sendFile(dir + "index.html");
});
app.listen(3000);
If you need to serve other static assets from within a folder, you can add something like this before you start defining the routes:
app.use(express.static('public'))
Let's say you have a js folder inside public like: public/js. You could include any of those files inside of your html files using relative paths. For example, let's say /contact needs a contact.js file. In your contact.html file, you can include the script as easy as:
<script src="./js/contact.js"></script>
Building off of that example, you can do the same with css, images etc.
<img src="./images/rofl-waffle.png" />
<link rel="stylesheet" href="./css/o-rly-owl.css" />
Hope this helps everyone from the future out.

Categories

Resources