Accessing local json files from the browser using NodeJs backend - javascript

I am working on a react application that takes the json file path as a parameter to render the json data in my ui. Accessing local files from the browser is restricted, so how can I create a backend server to retrieve my local json files and serve them to the browser?

you can boot up a local server using express, and use the fs module to access file content
const fs = require('fs');
const file_content = fs.readFileSync('./{file_name}',
'{content_formate}').toString();
// For show the data on console
console.log(file_content);
To create a server that is listening on port 3000, use
const express = require('express')
const fs = require('fs');
const app = express()
const port = 3000
app.get('/', (req, res) => {
const file_content = fs.readFileSync('./{file_name}',
'{content_formate}').toString();
res.send(file_content)
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
something like this

To access local json files in your swagger application, you need to use express - as the browser cannot access your local file system. You can create an endpoint, i.e. '/swagger', that will allow you to serve the files from the directory provided. In the urls parameter, you will use '/swagger/name.json', rather than the local path. Create a driver.js file with the following content:
var express = require('express');
var app = express();
app.use('/swagger', express.static('/path/to/local/files'));
app.listen(3000);

Related

How can i get response from another JavaScript file while working with nodejs and express?

I'm trying to learn nodejs and express and i created a simple server. I want to run some JS code for response.
When I used this method it's works.
const express = require('express');
const path = require('path');
require('dotenv').config();
const app = express();
const port = process.env.PORT || "8000";
app.get('/', (req, res) => {
res.send(`<script>
console.log("Program works!");
</script>`);
});
app.listen(port, () => {
console.log(`Listening to requests on http://localhost:${port}`);
});
But writing JS as String is hard so I tried this:
const express = require('express');
const path = require('path');
require('dotenv').config();
const app = express();
const port = process.env.PORT || "8000";
app.get('/', (req, res) => {
res.send(`<script src="./response.js"></script>`);
});
app.listen(port, () => {
console.log(`Listening to requests on http://localhost:${port}`);
});
And i get this error:
GET http://localhost:8000/response.js net::ERR_ABORTED 404 (Not Found)
When you send this:
<script src="./response.js"></script>
to the browser, the browser will parse that and see the src attribute and will then immediately request ./response.js from your server. But your server doesn't have any route to respond to that request (thus it gets a 404 error back from your server). Remember that a nodejs server serves NO files by default (unlike some other web servers). So, you have to create routes or middleware for anything that you want it to serve.
So, you need to add a route to your server that will response to a request for response.js. First change your <script> tag to this:
<script src="/response.js"></script>
You want the request to be "path absolute" so it does not depend upon the path of the containing page. Then, you need to add a route handler for response.js to your server.
This can be done as a single route:
app.get('/response.js', (req, res) => {
res.sendFile("response.js", {root: __dirname});
});
Or, you can use express.static() to serve a whole directory of publicly available files with one line of code (if you also move all publicly available static files to their own directory away from your server files).

Use Node for send and receive pdf files

i'm using Express to create a backend server using NodeJs. One of the functionalities of the project is to send and receive PDF files. The other routes of the backend send and receive JSON files but i want to create a route for send and receive PDF files, what can i do? What i have until now:
const express = require('express')
const app = express()
const db = require('./config/db')
const consign = require('consign')
const consts = require('./util/constants')
//const routes = require('./config/routes')
consign()
.include('./src/config/middlewares.js')
.then('./src/api')
.then('./src/config/routes.js') // my routes file
.into(app)
app.db = db // database using knex
app.listen(consts.server_port,()=>{
//console.log('Backend executando...')
console.log(`Backend executing at port: ${consts.server_port}`)
})
app.get('/',(req,res)=>{
res.status(200).send('Primary endpoint')
})
/* basically at routes.js file i'm handling http routes that manages JSON objects such as this one below:
*/
At routes.js:
// intercept http routes and pass specific funtion for handling them
module.exports =app=>{
app.route('/products')// regular JSON objects
.post(app.src.api.itensVenda.saveItem)
.get(app.src.api.itensVenda.getItems)
.put(app.src.api.itensVenda.toggleItemVisibility)
app.route('/articles')
.get(app.src.api.articles.getArticle)
.post(app.src.api.articles.saveArticle)
// the route above is the one that i want to use for sending and receive PDF files
app.route('/info')// ordinary JSON objects
.post(app.src.api.info.saveInfo)
.get(app.src.api.info.getInfo)
}

Express routes work when serving locally but fail once deployed

I am building a blog using Node js and Express and hosting it on firebase. When I serve the website locally everything works just fine and the html is served as expected. But, when I deploy the server the routes no longer work and the html files can't be found. I'm sure it has to do with how firebase deploy hold the html files.
I'm not really sure where to go from here. I can't really find great guidance on how to set up something like this on the firebase docs.
const functions = require("firebase-functions")
const cors = require("cors")
const express = require("express")
const path = require("path")
/* Express with CORS */
const app = express()
app.use(cors({ origin: true }))
app.get("/", (request, response) => {
response.send("Hello from Express on Firebase with CORS!")
})
//File path consts
const publicDir = "/Users/wilson/wildman-talks-fb/public";
const blogDir = "/Users/wilson/wildman-talks-fb/public/blogs";
app.get("/about/", (req, res) =>{
res.sendFile(path.join(publicDir, "/about.html"));
});
app.get("/contact/", (req, res) =>{
res.sendFile(path.join(publicDir, "/contact.html"));
});
app.get("/tools/", (req, res) =>{
res.sendFile(path.join(publicDir, "/tools.html"));
});
app.get("/five-steps-july-20/", (req, res) =>{
//res.send(path.join(publicDir, "/five-steps-july-20.html"));
res.sendFile(path.join(publicDir, "/five-steps-july-20.html"));
})
exports.app = functions.https.onRequest(app)
So what is happening is when I deploy the site locally all of the links in my webpage work to other html webpages for my site. When I deploy it on firebase I get 404 errors. I was able to use path.join(__dirname, "../public") and print out all of the files contained there. When i did that these were the files that were there on my local host: [".DS_Store","404.html","about.html","blogs","contact.html","css","five-steps-july-20.html","img","index.html","js","mail","tools.html","vendor"]. After deploying it just returns me a 500 error so I guess that won't help.
Your directories contain absolute paths to your filesystem. Try to use dynamic absolute paths.
Change the paths from
const publicDir = "/Users/wilson/wildman-talks-fb/public";
const blogDir = "/Users/wilson/wildman-talks-fb/public/blogs";
To
const path = require("path");
const publicDir = path.join(__dirname, "/public";)
const blogDir = path.join( __dirname, "/public/blogs");

How to add Express route endpoints from another .js file?

I have an Express app whose server.js file has maybe 30 GET and POST endpoints, like this:
const express = require('express');
const app = express();
const http_port = 8000;
app.listen(http_port,()=>{
console.log(`app listening on port ${http_port}`);
});
app.get('/create_something',function(req,res){
createSomething();
res.send('create');
});
app.post('/update_something',function(req,res){
updateSomething();
res.send('update');
});
//and so on for 30 more endpoints
For ease of maintenance, I want to break this set of endpoints up into different files, e.g. video.js and audio.js.
Thinking this solution might help, I created another file other_route.js:
var express=require('express');
var router=express.Router();
router.get('/other_route_endpoint',function(req,res){
res.send('other_route_endpoint');
});
module.exports.router=router;
and then including this in server.js by changing my initial declarations to:
const express = require('express');
const app = express();
const http_port = 8000;
var router=express.Router();
router.use('/other_route',require('./other_route').router);
But when I visit myserver.com:8000/other_route_endpoint, I get this error:
Cannot GET /other_route_endpoint
How can I add in endpoints from other files into server.js, so I can move some of its many endpoints into these subfiles?
First, your main file should not be using a router. Change the line to app.use('/other_route',require('./other_route').router);.
Second: each path you set with router.use in the routing file will be relative to the path specified in app.use. See https://expressjs.com/en/guide/routing.html#express-router
For example, if you have this in your main file
app.use('/foo', require('./bar.js'));
And this in bar.js
router.get('/bar', /* do something */);
Then the corresponding endpoint would be /foo/bar.

express.js to GET json file in terminal

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();
});
});

Categories

Resources