How to create custom endpoints on the fly with nodejs [closed] - node.js

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 1 year ago.
Improve this question
I have a website and when I click on a button I want to generate a custom link for the user, a link that it will be a endpoint to my nodejs server. My question is: how can this be accomplished ? I think I need to make a basic endpoint in my server that will be called when I press that button in my website and then, based on a custom property in the request's body, it will generate another endpoint, a custom endpoint for that user. How can I do this ? Any help or documentation would be appreciated.

Usually, this would be done with a parameter added to a fixed part of the URL. You then define a route for the fixed part of the URL and the code for that route then examines the parameter and acts accordingly. This way, you're dynamically generating parameters, but all the new parameters all go through the same route definition and the same code.
You can either use a dynamic portion of the URL path or a query parameter. Here is an example of each:
// dynamic path segment
// example url /dyn/dieutaoc
app.get("/dyn/:id", (req, res) => {
// use req.params.id to access the dynamic part of this path
});
// dynamic query parameter
// example url /dyn?id=dieutaoc
app.get("/dyn", (req, res) => {
// use req.query.id to access the dynamic part of this path
});

Related

Internal API calls and communication between NextJS app and express server [closed]

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.

Best practice for validating API input in Node.js? [closed]

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.

What is best practice when implementing an Admin Panel for a MEAN Application [closed]

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

how to generate api documentation [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
I need to write some api documentation for a REST API that I've created. Are there tools that will stub out a nice html output similar in style to the underscore api documentation? Or perhaps something that will output something as a twitter bootstrap styled html?
I see that docco does annoated code, but I'm actually just looking to document the API only. Ideally I'd like to point a tool at the controller file and have it generate documentation about the methods and routes but not show any source code unless I specifically call out examples.
apiDoc creates a documentation from API annotations in your source code.
Integrated is an API history, with that various API version levels can be compared.
So it can be retraced what changed in the API since the last version.
Demo: http://apidocjs.com/example
Github: https://github.com/apidoc/apidoc
Check out I/O Docs on Github - http://github.com/mashery/iodocs . It's hacked in Node.js, and has a lot of community contribution/involvement. To see it working in the wild:
http://iodocs.docusign.com
http://console.datasift.com/datasift
Uber simple configuration schema (JSON), and hell, if you don't want to describe it all by hand in JSON, use I/O Doctor, a web-based tool for importing/building JSON configs with a UI:
http://iodoctor.net/
Also available on Github at https://github.com/brandonmwest/iodoctor
Let me know if I can help you get started. There are plenty of example configs in the I/O Docs repo. Take care.
I/O Docs or Swagger, which are the most popular RESTful API documentation systems. There is also RAML and Apiary.
test2doc.js helps you generate API documentation from your tests/specs. So you can always get the latest update-to-date API documents, populated with real request/response data.
Test code example:
const doc = require('test2doc')
const request = require('supertest') // We use supertest as the HTTP request library
require('should') // and use should as the assertion library
// For Koa, you should exports app.listen() or app.callback() in your app entry
const app = require('./my-express-app.js')
after(function () {
doc.emit('api-documentation.apib')
})
doc.group('Products').is(doc => {
describe('#Products', function () {
doc.action('Get all products').is(doc => {
it('should get all products', function () {
// Write specs towards your API endpoint as you would normally do
// Just decorate with some utility methods
return request(app)
.get(doc.get('/products'))
.query(doc.query({
minPrice: doc.val(10, 'Only products of which price >= this value should be returned')
}))
.expect(200)
.then(res => {
body = doc.resBody(res.body)
body.desc('List of all products')
.should.not.be.empty()
body[0].should.have.properties('id', 'name', 'price')
body[0].price.desc('Price of this product').should.be.a.Number
})
})
})
})
})

Node.js redirect to another node.js file

I want to do a re-direction from one nodejs file to another nodejs file. I used res.redirect(URL), but when execute it says "cannot GET /nodepage"
Currently I am using
// Handler for GET /
app.get('/nodepostgres', function(req, res){
res.redirect('/nodepost.js?a=1');
});
I think there are a few things that you don't explain properly or don't understand properly in your question.
I am not sure what you mean about "re-direction from one nodejs file to another nodejs file". You seems to think that a node script file correspond to a URL (or a page). That's wrong. A node script correspond to an application that may (or may not) expose several pages through several URL and can imports application logic from other script files (you will run a single root script file for a site or application). It's totally different from what you may know with (vannilla, no framework) PHP.
Exposing different pages through different url is called Routing, all Express documentation about routing can be found here.
What I understand is that your trying to make a function / page / Url per script : nodepost.js file is a page. Code organization is a good thing but let's focus on how node + express works first.
From what I understand, you're applicaton has a few exposed url, let's say :
"/" homepage
"/nodepostgre" (maybe accepting an 'a' arg ?)
"/nodepost" accepting an arg : a
Note : we forget the id of file = page, we don't want an extension to appear on URL so nodepost.js becomes nodepost
What you can do is setup the 3 url expositions :
app.get('/', function(req, res) { res.render('home'); }); // render the home page
app.get('/nodepost', function(req, res) { // expose the nodepost function
var a = req.params.a;
doSomethingWith(a);
// res.render, res.send ? whatever you want...
]);
app.get('/nodepostgres', function(req, res){ // use of res.redirect(url[, status])
res.redirect('/nodepost');
});
Is that what you want ?
Then, here is a more elegant way to handle params ("a").
app.get('/notepost/:a', function(req, res) { // called via /nodepost/here_goes_a_valu ; no "?"
var a = req.params.a;
});
Why is it better ?
Respect REST (may not be the best link to describe rest but...)
Allows you to expose '/nodepost' without params
Certainly one million other things

Resources