Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 months ago.
Improve this question
I have a NextJS app with a custom express server. My pages/index.js is making an internal call to my express route /api/users. This is done using isomorphic-unfetch inside getinitialprops() like this:
const res = await fetch('http://localhost:3000/api/users');
My custom express server on top of NextJS has API routes that send back JSON data. Like so:
//some code before
const app = next({ dev })
const handle = app.getRequestHandler()
let apiRoutes = require('./routes/apiRoutes.js');
app.prepare().then(() => {
const server = express()
server.use('/api', apiRoutes);
server.get('*', (req, res) => {
return handle(req, res)
})
//more code
So my question is, is this the way to communicate between the my client side code and server side code? If so:
How do I protect these endpoints so that the user doesn't just type in myNextJSwebsite.com/api/users and get a JSON response?
This is a common pattern to separate between api & renderer.
In order to secure your api end-point you will need to implement some kind of authorization, there is common lib for auturization in express, called passport, you can check the types, it supports most of the common methods.
I personally prefer the JWT way, because it allows to work with many instances of my server due to the fact that there are no user session on the server.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I had successfully installed and and run admin-lte in my Node.js project. As we know they are providing us login, register and forgot password pages for ready to use.
So if I want to make an API (and that API is also made in Node.js) call on one of the page then what steps should I follow?
You should render html page in nodejs (for example inside express.js) and in express.js you can use template engine like: EJS - hbs ... see this Link.
And for use API inside adminLTE you should use front end web frameworks like: reactjs - angular - vuejs or use old jquery and etc. You can even render static web page and send data into template engine via Expressjs template engine, I explained above.
ReactJS version of the original AdminLTE dashboard: https://github.com/booleanhunter/ReactJS-AdminLTE
AdminLte for Angular 2:
https://github.com/mledour/angular-admin-lte
See this example for load static web page with hbs:
const express = require('express');
const app = express();
const port = 3000;
//Loads the handlebars module
const handlebars = require('express-handlebars');
//Sets our app to use the handlebars engine
app.set('view engine', 'handlebars');
//Sets handlebars configurations (we will go through them later on)
app.engine('handlebars', handlebars({
layoutsDir: __dirname + '/views/layouts',
}));
app.use(express.static('public'))
app.get('/', (req, res) => {
//Serves the body of the page aka "main.handlebars" to the container //aka "index.handlebars"
res.render('main', {layout : 'index'});
});
app.listen(port, () => console.log(`App listening to port ${port}`));
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I am developing a mobile app, with the backend in Node.js. Users will interact with the platform almost exclusively through the mobile app. As part of the backend, I am exposing multiple APIs to be utilized by the mobile app -- for example: an API to create an account, send a message, post a picture, etc.
What is best practice to validate the API input?
My thought is to create a module for each API, whose purpose is to extract, sanitize, and validate the relevant attributes from the http-request. For example, the "create an account" API will have an associated AccountCreationRequest module with a validate method in which all account-creation-specific validations will be defined. Each specific validation can then be performed by libraries such as express validator and validator.
exports.AccountCreationRequest = {
init: function(request) {
... extract attributes ...
},
sanitizeAndValidate: function() {
... use express-validator/validator on
attributes such as username, email, etc ...
},
isValid: function() {
... return result of validation ...
}
};
Then, when the backend API receives a request,
var accountCreationRequest = AccountCreationRequest.init(httpRequest);
accountCreationRequest.sanitizeAndValidate();
if (accountCreationRequest.isValid()) {
... store in database and notify client of success ...
} else {
... notify client of failure ...
}
My concern is that N APIs will require N request-validation-modules. However, since each API is unique, I don't think there is much opportunity for code reuse.
If you use express, you can do something like
app.use('/private', function(req, res, next) {
if (/*some condition to check for authentication*/) {
next();
} else { //unauthorized
res.status(401).send('not authorized, please authenticate');
}
});
that will filter everything under the /private path through your authentication condition. You can also use wildcards in the path if you prefer.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I am a complete beginner to all aspects of the MEAN stack. I have a minimal implementation of an application that pulls data from a MongoDB and displays the data on an angular front end using a RESTful API. The front end was generated using yeoman. I used this tutorial: https://www.youtube.com/watch?v=OhPFgqHz68o
I have done some research into admin panels that I can integrate with node and best practices. I have found ready made panels such as this one: https://github.com/jedireza/drywall
My Questions are as follows:
How do I go about directing a user to either my application or the admin panel at login? Do I use express for this?
If I wanted to implement drywall (link posted above), how could I go about integrating it with my current application? i.e. Do I have to download drywall and then write my code within the files that come with it, or can I somehow integrate it with my currently written application?
I use Angularjs for the front end and Node.js with Express at the backend.
I am going to paste one demo of my routing.
Angular JS Routing Example - Using Routing Module
app.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/txn_history', {
templateUrl: 'views/add_user.html',
controller:'mainCtrl'
})
Express JS
Attached the directory for usage
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }))
app.use(express.static(__dirname + '/test'));
Using Routes Module for Node & adding a JS file that has function to add user
var routes = require('./routes');
var route_add_user = require('./routes/add_user');
Calling the function with the route here; .adduser is function name within that js file
app.get('/adduser', route_add_user.adduser);
I hope this helps
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
During the last months, we at work have been looking for a solution to the following problem: front-end developers can't easily modify the appearance of the website without the help of back-end devs.
Our culture as a team is mostly based on full-stack frameworks such as Symfony 2 and Ruby on Rails. We use templating engines but the templates are mostly written by backend-devs according to designers' markups.
The step we are considering to make is separating that monolithic architecture into a backend rest API and a NodeJS server as "UI server". The NodeJS server would handle the client request, consume the backend API and return a rendered template. By specifying clearly the API and the JSONs served, frontend and backend devs could then work in parallel with less problems. More info here: http://www.nczonline.net/blog/2013/10/07/node-js-and-the-new-web-front-end/
The thing is, we strongly believe that this separation is a good thing from an architecture POV, but we fear about the drawbacks. We suspect that it will make things way harder. None of us in the team has never worked with this kind of architectures, so any hint or experience about that would be very valuable.
Is it worth it? When? Why?
What you need to do, is to have a clear line that separates your front-end from back-end. Then whatever the front-end needs from the backend-end team, it will documented comprehensively.
Let's say what you currently have is something like this:
app.get('/', function (req, res) {
database.query('select * from user', function (err, result) {
res.render(result);
});
});
But then then you want to make it like this:
in UI server:
app.get('/', function (req, res) {
request('apiServer/user', function (err, result) {
res.render(result);
});
});
in API server:
app.get('/user', function (req, res) {
database.query('select * from user', function (err, result) {
res.send(result);
});
});
This is good. This will separate the front-end and back-end, but not only logically but also physically by being in different servers.
I believe if they are under the same server it will be just ok. Instead of above, just have them in different files:
in user.js:
exports.getAll = function (cb) {
database.query('select * from user', cb);
};
in server.js:
var user = require('./user');
app.get('/', function (req, res) {
user.getAll(function (err, result) {
res.render(result);
});
});
Why this is better than your solution? Because it separates touching database, and rendering the data, and also it doesn't have a extra http round trip.
Following a MVC pattern, you put files that are like user.js in a models directory, you put files like server.js in a controller directory. You make sure both are documented for front-end developers.
Now if your front-end developers are just gonna make UI changes, they will just touch the HTML files. If they want to add a section with data, they will read the backend documentation, they will add another call to the model to get the data they in the respective controller that renders the HTML.
Just make sure you will standardize everything, so when something new comes along, programmers in your team can somehow predict how the interface is going to be, use a good ORM to the heavy lifting on making database calls. If using an ORM is not your choice then make good abstractions.
So your application in layers can be like this:
Database --> ORM --> Models --> Controllers --> Views(HTML files)
Now the front-end developers, work on the right side the above diagram. They only need to know the documented API of their left side if it's nicely abstracted away, but they don't need to know how it works. Anyone who works on the controllers, only need to know the documented API of their left side which is Models. You can continue it all the way to the database on the left.
Then on each layer you can have unit tests and integration tests all the way to the front to make sure the interfaces are consistent.
And if you're team is large, with a large code base, make sure you always keep the backward compatibility in your interfaces, but with warnings in logs for deprecated stuff. Never try to break anything.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I would like to know the structure of a typical NodeJS app, because the more I read and see the projects, the more confused I am, specifically for questions like these (or even more after I updated this question):
Take the MEAN stack for example, from what I know, NodeJS and Express take care of the server part, providing the server interface, etc. MongoDB and Angular are pretty straightforward.
But where should the business logic go? Say if I have a controller.js which contains a function, and the route.js file binds the request with this controller function. My question is: under which module these files belong to/run under (Express or NodeJS?)
Where is the starting point of a NodeJS app? Say index.php is the starting point of a PHP app, but where is it for NodeJS app? I can see that all Nodejs projects have a file called server.js or app.js, etc.(containing something like module.exports = app;) But how can NodeJS know which file to find and execute?
I am a fresh noob on NodeJS, Express, sequelize.js/Mongoose, Jade/EJS but want to get started on a NodeJS project. Could you please elaborate on the actual function that each modules provide and a general introduction of the typical structure for a full JS stacked NodeJS app? Thanks in advance!
Alright, this is a pretty broad question and I'm definitely no expert, but I'll do my best here.
TL;DR
routes are controllers that tell what logic to execute when a user navigates their browser to a certain path within your app, including which views to render and what data to send to those views
models are just that - data models within your application
module.exports = tells a file what exactly it "exports", that is what code needs to be executed or accessible from your main app file.
require(..) includes a module. You can set this on a variable so that you may call module functions later, or simply execute a function if that is all that module.exports returns.
Combining these techniques can help you nail down a solid framework for any of your applications.
Long Answer
Express provides a solid framework for structuring your Node.js application. Node is completely independent of Express, but because of how popular Express is they practically go hand-in-hand. Once installed, Express can be used to generate a scaffold web project (with options) for you to build on top of if you'd like.
Controllers
A generated project will create /routes/index.js, which (if you understand MVC) is essentially your main controller. A route in express is written as so:
app.get('/path', function(req, res, next){ .. } );
Lets break that down: our application variable (app) is being told that on a GET request to '/path' to execute an anonymous callback function with req, res, next variables (request, response, callback respectively). I find it helpful to think of this like a custom event handler.
Its important to note at this point that we could also call app.post with the same syntax for posts to a URL as opposed to gets.
Within our anonymous callback, we handle any incoming data and render a view for the user. This is where most of my business logic ends up, so it actually makes sense to NOT use anonymous functions here. Here's an example of a basic callback that just displays a homepage:
app.get('/', function(req, res, next){
//some business logic
res.render('views/home');
});
When the user tries to GET the index path of our application (/), we simply render our home view that, from the root of our project, is stored in a views folder.
But what if we want to modularize this so that we aren't declaring all of our routes in our main app.js or server.js?
We use module.exports = .. in our modules to tell our server what exactly to include. In my controller, I export a single function that takes the application as an argument and uses that to define our routes like so:
Controllers/User.js
module.exports = function(app){
app.get('/users', function(req, res){
var users = req.db.collection('users').find();
if (!users) {
console.log("no users found");
res.redirect('/');
} else {
res.render('users/index', {users : users});
}
});
};
Don't worry about the req.db code, I attach the database to the request in my application but that isn't done by default. Simply understand that I'm getting a list of 'users' here, and redirecting the user to the index of my app if there aren't any.
Models
Mongoose provides us with a great interface for writing models. With mongoose, writing models is a three step process:
Define a schema
Define model logic
Generate and export the model
Here is an example of a User model:
Models/User.js
var mongoose = require('mongoose'),
userSchema = new mongoose.Schema({
name: { type: String, required: true },
joinDate: {type: Date, default: date.now }
}),
User = mongoose.model('user', userSchema);
module.exports = user;
Server App
module.exports is used to help us define some modularity to our codebase. When we run a node application, we're ultimately running a single JavaScript file (you've already seen that file with server.js or app.js).
To keep this file from getting too big with multiple models and routes, we use require(module) to include code from other JS files. module in our case would be a path to the module we want to require. If you have the following doc structure:
| Controllers
- User.js
| Models
- User.js
| Views
app.js
To include your user controller from app.js, you would write: require('./Controllers/User'). Since our controller modules simply export functions, we can call that function immediately after our require statement by simply adding parentheses at the end (with whatever parameters are required). Including my controllers looks like so:
require('./Controllers/User')(app)
I'm passing in the actual app, because my module (below) simply exports a function that adds business logic to my app's routes. This only needs to be called and never used, so I don't capture my controller as a variable to call methods on later.
Including models is a little different, since we may want to perform some operation that our model defines. We can do this by changing up our require code just a bit:
var User = require('./Models/User');
Now we can call methods of our User model whenever. Mongoose gives us a lot of base functionality for free:
User.find({}, function(err, users){ .. });
The above function will go find all of our users, and then execute an anonymous function with a potential err (is null if no issues) and then a list of our users in JSON format. Pretty nifty.
Combining all of these concepts is how you create a basic web application using Express and Node.js. Please let me know in the comments if there's anything I can clarify about how I use Express. This is very surface level knowledge, and I suggest digging into documentation and looking at plugins to extend the capabilities of your apps. Good luck!