Express API Versioning with query params - node.js

I'm a NodeJS beginner and I'm developing an API backend using Express.
I have read many articles about how to do API versioning with Express but none of them explains how to use the query params approach.
I like doing API versioning like:
example.org/users?version=1.0
example.org/users?version=1.1
example.org/users?version=1.2
Etc. How can properly handle and structure my API code to achieve this?

You can do something like that (this is just an example, you can play arround with it in many ways)
index.js:
var express= require('express')
, app = express()
, usersHandlers = require('./handlers/users');
app.use("/users",usersHandler);
function usersHandler(req,res){
var version = req.query.version;
console.log("This code is relevent for all versions");
usersHandlers[version](req,res);
}
app.listen(8000,function(){
console.log('Server running at http://127.0.0.1:8000/');
});
users.js:
module.exports = {
'1.0' : function(req,res){
res.send("This is the response for version 1.0");
},
'2.0' : function(req,res){
res.send("This is the response for version 2.0");
}
}

Related

GET POST requests in node js

Hi friends I'm new in MERN application build I want to know that How we can handle requests in nodeJs and connect mongoose to the database. Please help me out.
I would recommend the library Express.js, but you could also use another one if you want to.
Here's an example for how this could look like in Express:
const express = require('express');
const app = express();
app.use(express.json()); // necessary for req.body
app.post('login', function(req, res){
let data = req.body;
// do something..
res.sendStatus(200);
});

Openui5 jquery POST to Node.js Server contains empty request body on server side

I am setting up a sample App using Openui5 as frontend framework, Node.js & Express.js for backend API and MongoDB as database.
My JQuery Ajax post does not contain any body data when arriving at the backend.
I tried several of the solutions provided on stackoverflow, but none of them seems to work for me. MongoDB and Backend Server are running. Data fetching is also working with ui5 data binding to XML View.
controller.js:
onSave: function () {
//get user input from local json model
var oNewEmployee = this.getView().getModel("newEmp").getProperty("/newEmp"),
data = JSON.stringify(oNewEmployee),
url = 'http://localhost:3000/employee';
//do the post
$.ajax({
url : url,
dataType : 'json',
contentType : 'application/json',
data: data,
type : 'POST',
success: function(response){
console.log(response);
}
});
},
server.js:
var express = require("express");
var app = express();
var mongoose = require("mongoose");
var cors = require("cors");
app.use(cors());
mongoose.connect("mongodb://localhost/schichtplaner", { useNewUrlParser: true });
app.post("/employee", function (req, res) {
console.log(req.body);
});
app.listen(3000);
I keep getting undefined as output from console. Would be great if someone has an idea how to solve this.
You should use the body-parser npm module in order to read the POST request payload.
https://www.npmjs.com/package/body-parser

ExpressJS Middleware Method to make variable available in other (module) files

I am playing around with making a NodeJS app that combines REST API functionality with MongoDB CRUD persistence. I'm pretty new to NodeJS.
Right now I've managed to connect to the Database and figured out that the rest of my code belongs inside the callback - ie only process REST request after the DB is up and available.
The challenge I'm running into in this case is understanding how to "attach" the 'client' (from mongodb.connect) to the 'request'. I need to somehow make it available in other files because I want to keep my routes separate as a best practice.
The same question applies to any variables in the main server.js file which I need to be able to access in my modules.
Here is the relevant code:
//server.js
const express = require('express')
const mongodb = require('mongodb')
const bodyParser = require('body-parser')
const routes = require('./routes')
const url = 'mongodb://localhost:27017/testDB'
let app = express();
app.use(logger('dev'))
app.use(bodyParser.json())
mongodb.connect(url, {useNewUrlParser:true},(error, dbClient) => {
if (error) {
console.log(`Error: ${error}`)
process.exit(1)
}
//connected
console.log(`Connected to mongoDB`)
//what do I do here to make sure my routes can access dbClient?
app.get('/accounts', routes.getAccounts(req, res) )
app.listen(3000)
})
//./routes/index.js
const bodyParser = require('body-parser')
const errorhandler = require('errorhandler')
const mongodb = require('mongodb')
const logger = require('morgan')
module.exports = {
getAccounts: (req, res) => {
console.log("in getAccounts")
//how can I use dbClient in here?
}
}
Thank you in advance for your help!
My apologies if anything about my post isn't according to the normal standards, I'm brand new here! All critique appreciated, coding and otherwise!

Node.js / express / passport / saml - How to inspect the content of outgoing HTTP request to SAML Identity Provider?

I am a newbie in node.js, but I have a sample application written for node.js that shows the way of integration with specific Identity Provider (SAML). Using this sample app I am trying to inspect what is sent in the HTTP requests made from the node.js backend to the remote IdP. Logging the request headers and body by writing to the console.log would be enough for me. Monitoring the network traffic with some tool like Fiddler is not an option for me, because I cannot run it locally, I need to have the app exposed and I have it deployed to Heroku.
I've tried morgan, but it only intercepts the INCOMING requests. I've also tried global-request-logger, but for some reason it does not inject itself into the express framework and passport. Seems like passport is not using the standard modules for HTTP requests?
The question is: what I need to use to be able to log the content of the HTTP requests made by passport during the .authenticate() call? Is there any flag that I am able to set in passport to enable HTTP logging? Or should I rather do it in express? Or maybe some other package would provide the functionality I need?
EDIT:
My original question was marked as possible duplicate of how to log OUTGOING https requests from node within webstorm
But actually I have already seen that topic and I've tried to setup a hook to http module, it was done this way:
'use strict';
// Setup express.js application:
var express = require('express');
var app = express();
// Patch "http" module with outgoing request logging:
var http = require('http');
const originalRequest = http.request;
http.request = function wrapMethodRequest(req) {
console.log('EXTERNAL OUTGOING REQUEST LOGGING:');
console.log(req.host, req.body);
return originalRequest.apply(this, arguments);
}
This approach was not working. As already said in the original question, it seems that passport does not use standard http module? Or did I something wrong with the code above?
As already mentioned in the original question, I was also trying to handle it via global-request-logger package (which as explained in the possible duplicated post, uses the same technique). The code for that was:
'use strict';
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var passport = require('passport');
var SamlStrategy = require('passport-saml').Strategy;
app.use(bodyParser.urlencoded({ extended: false }));
var globalLog = require('global-request-logger');
globalLog.initialize();
globalLog.on('success', (req, res) => {
console.log('HTTP(S) CALLOUT SUCCESS');
console.log('REQUEST: ', req);
console.log('RESPONSE: ', res);
});
globalLog.on('error', (req, res) => {
console.log('HTTP(S) CALLOUT ERROR');
console.log('REQUEST: ', req);
console.log('RESPONSE: ', res);
});
...

Mock up SharePoint Rest API using NodeJS and ExpressJS

I'm trying to create a development environment for a small sharepoint application. The application queries a couple of Sharepoint 2013 lists and builds a custom view of the data. Rather than publishing to sharepoint every time I make a change I would like to use NodeJS and Express 4 to mock up the api. I don't need to mock up any of other CRUD activities; just the GET requests.
I started out using the following:
const express = require('express')
const fs = require('fs');
const path = require('path');
const csv = require('csvtojson');
const app = express();
function openAndSend(file, res){
csv().fromFile(path.join(__dirname,file))
.then(jsonarray)=>{
res.setHeader('Content-Type','application/json');
res.send({d:{results:jsonarray}});
});
}
app.get('/dataset',(req,res)=>{
openAndSend('./data/dataset.csv', res);
});
app.get('/people',(req,res)=>{
openAndSet('./data/people.csv', res);
});
How can I use express js to mock up something like
/api/lists/getbytitle("Data Set")/items and /api/lists/getbytitle("People")/items
I tried changing the app.get functions to app.get('/api/lists/getbytitle("Data%20Set")/items', ....); which did not work. However removing get getbytitle("...")" routed correctly.
I was able to solve the issue using express Router and a regex expression for the path/route. The most challenging part was discovering that special characters needed to be encoded.
var router = express.Router();
router.get(/getbytitle\((%22|')Data%20Set(%22|')\)\/items\/?$/i,(req,res,next)=>{
openAndSend('./data/dataset.csv', res);
});
router.get(/getbytitle\((%22|')people(%22|')\)\/items\/?$/i,(req,res,next)=>{
openAndSend('./data/people.csv', res);
});
app.use('/_api/lists',router);

Resources