Express JS Basic Routing Template - express

Can someone explain this to me clearly?
const express = require("express");
const app = express();
I get the first line of code, but don't get the concept of initializing a variable "app" as express()? When we import express, we also have access to express()?
What does it do theoretically? What does that () of express() do?
Do we always have to do it like that?
Thank you.

If you are familiar with object-oriented programming, then the way to think of this is by creating an instance.
When you import express, you are importing the class. However, your server is an instance of that class. So, when you call
const app = express();
you are spinning up your server. You now have the encoding of a server you can interact with from app, whereas the original import just refers to the same class (i.e. like a template) for what that server is. The function express() is merely initializing a new server object for you.
Technically, you could have multiple 'servers' running:
const app1 = express();
const app2 = express();
You would want these to be independent of each other, which is why you don't just use the top-level import.

According to the documentation
The express() function is a top-level function exported by the express module
The function returns a app object which is essentially an Express application.
The app object has methods for
Routing HTTP requests; see for example, app.METHOD and app.param.
Configuring middleware
Rendering HTML views; see
Registering a template engine; see app.engine.

Related

How to inject a request (bypass HTTP protocol stack) in nodejs express?

Imagine this sample Express app straight from the documentation:
const express = require('express')
const app = express()
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(3000)
What is the idiomatic way to invoke the '/' endpoint programmatically from a different point in the same application code? Assume that I already removed the last line app.listen(3000).
The reason for this is that I want to take something like express-pouchdb and write an adapter for a different wire protocol, but leveraging the extensive routes already defined. I want to invoke these routes directly from js code without going over the network.
The application has dozens of routes already defined so changing each one to direct function calls as suggested in the first comment is not an option.
UPDATE:
I tried calling app.route.dispatch() but nothing comes back on the rsp object.
Your question is a duplicate of this answer: Is it possible to call Express Router directly from code with a "fake" request?
You can use run-middleware module exactly for that. You create an express app a usual, and then you can call the app using your parameters

How to seperate business logic from controllers in Express.js applications

During one of the interviews I got a question how to separate business logic from controller in Express. Would be that a correct solution?
const db =require('./db')
const helpers =require('./helpers')
exports.getBooksValue = (req, res)=>{
const books = db.get(req.params)
const booksValue = helpers.calculateBookValue(books)
res.send(booksValue)
}
Actually there is no correct(standard) solution in express whereas ruby on rails for example has mvc pattern in its standard way since express encourages more flexibility.
Your solution looks good, but if you are focusing on further seperation,
I suggest you to make config folder and managing db's information inside of that file.
Inside of config folder, make sure to seperate whether it is for production or development.
You can also use dotenv in config folder for importing env values more safely.

How To Overcome CORS issues with Redux React Express and Node?

I have a React App that uses React Router and Redux as its state manager. The server side of the app uses Express and Node.
I am making API calls to an external service. I do not have the ability to enable CORS on the external service. Therefore, I need to use my app's server side to make the calls to the external service to remove the browser from the equation, and eliminate any CORS error.
I am able to get my data from the service on the server side successfully. I would like to know if it is possible to share the Redux store in between the client and server with some sort of middleware (looking for examples/resources).
The goal:
1) Handle a click event in the client
2) Have that event call a server side route to external api (don't know how to do this)
3) Then the server handles this route, makes the request, and sends the response to the client (through the shared react store - not sure if this is possible)
4) The store gets the new state, and then sends to the client side components, and the UI updates
Are there any examples/tutorials of this? Not looking for an initial server rendered page, but guides that inform how the above 4 steps can generally be implemented.
Thanks for the suggestions.
It turns out that I was severely over thinking the solution. All I really needed was the ability to launch a server side function (get resources from external API) from the client side event (load component). Sort of like how submitting a form, has an action that launches a server side function.
In my component:
componentDidMount() {
const product_api_results = productApi.getProductItems()
console.log('product_api_results in CART Component: ', product_api_results)
/* now I have results and can put it in the Redux Store via action to reducer for other components to work with on client */
}
The productAPI.getProductItems() that the component calls:
export function getProductItems () {
return axios.get('/api/get-products') // triggers a server side route
.then(function (response) {
console.log('client side response: ', response)
return response
})
}
In Express server.js file, the server will see this url and then get the proper data. The shopify.get() is from the shopify-node-api module:
app.get('/api/get-products', function (req, res) { // '/api/get-products' called from client
shopify.get('/admin/products.json', function (err, data, headers) {
res.send(data)
})
})

understanding express code flow

I am learning and trying to understand expressjs deeply.
var express = require('express');
var app = express();
app.get('/', ...);
Could you please inform me where the app.get method is defined in the express module?
I want to learn the code flow.
All methods including app.get() are defined here followed by app.all().

Can I use multiparty for a single route in my express app?

I have an Express 3 app that uses bodyParser for most routes. (Most routes only accept multipart.) I have a single route that is going to be parsing files up to 1GB in size which bodyParser can't seem to handle. I would like to use multiparty for only this route so I don't have to rewrite the whole API. Is this possible?
You can supply middleware to a single route by doing this:
var multipartyMiddleware = function (req,res,next){
//put your code to parse multipart here and call "next" when done
}
app.post('/this/is/a/single/route', multipartyMiddleware, function(req,res){
//do normal business logic in this route and send the response
})
If you need to bypass the multipart parsing in the old bodyParser in express 3 you can replace this:
app.use(express.bodyParser())
with this:
app.use(express.json())
app.use(express.urlencoded())
This works because the source of the bodyParser middleware reveals that it is just a combo of three middleware parsers: multipart, json, and urlencoded.
see the connect 2.X source here: https://github.com/senchalabs/connect/blob/2.x/lib/middleware/bodyParser.js#L54