So I'm working with a project that recently switched over to Node from Rails, where one of my favorite features was how easy it was to create a simple REST API, like so:
localhost:3000/materials/ Gets a JSON document of all objects
inside materials
localhost:3000/materials/:id Gets a JSON output of the object with
that id, e.g. /materials/123123 gives me item 123123
localhost:3000/materials/ Gets a JSON document of all objects
inside materials
And so on. I'm using Mongo. Is there a way of doing this in Node, or is there a guide or a package I should install that can do this?
Check out LoopBack from StrongLoop Suite, it has a built-in RESTful api explorer that interacts with Mongo using the mongodb connector. http://docs.strongloop.com/loopback/#using-the-api-explorer and http://strongloop.com/strongloop-suite/loopback/
For example, you could create the "materials" model with just the following commands:
slc lb model materials and then the restful api will get auto-generated for you at localhost:3000/explorer.
You can use Restify, to build RESTful Web Services in Node.js
A good tutorial at: https://www.openshift.com/blogs/day-27-restify-build-correct-rest-web-services-in-nodejs
Express seems like what you want. You can specify routes very simply as follows:
app.get('/:collection', function(request, response) {
// the value of :collection is stored in request.params
var coll = request.params.collection;
var search = request.query; // a hash containing the querystring arguments
// do stuff with request body, query parameters, etc.
response.send(data); // send the response
});
app.get('/:collection/:item', function(request, response) {
var coll = request.params.collection;
var item = request.params.item;
// do stuff
res.json(data); // can also send a JSON response
});
Take a look at restgoose. It is a Typescript library that makes simple REST API development super simple.
https://xurei.github.io/restgoose/
Related
I want to write a NodeJS HTTP endpoint using Azure Functions.
This endpoint will be a POST endpoint which takes files and upload these to blob storage.
However, NodeJS multipart form data parsers are all in the form of httpserver or expressJS middleware.
Is there any available tools that can parse the multipart form data after it has all been received from the Function Application's wrapper?
Thanks!
To answer original question:
However, NodeJS multipart form data parsers are all in the form of
httpserver or expressJS middleware.
Is there any available tools that can parse the multipart form data
after it has all been received from the Function Application's
wrapper?
Even 2 years later after you asked this question state of multipart form data parsers is not great, like you noticed majority of them assume req object which is a stream and tutorials/demos show how to parse multipart/form-data with express or httpServer.
However there is a parse-multipart npm package which can process req.body from azure function and return you array of objects with code similar to following:
const multipart = require("parse-multipart");
module.exports = function (context, request) {
context.log('JavaScript HTTP trigger function processed a request.');
// encode body to base64 string
const bodyBuffer = Buffer.from(request.body);
const boundary = multipart.getBoundary(request.headers['content-type']);
// parse the body
const parts = multipart.Parse(bodyBuffer, boundary);
context.res = { body : { name : parts[0].filename, type: parts[0].type, data: parts[0].data.length}};
context.done();
};
(original source: https://www.builtwithcloud.com/multipart-form-data-processing-via-httptrigger-using-nodejs-azure-functions/)
One area where I noticed parse-multipart can struggle is parsing forms with text fields. A slightly improved version which handles it better is called multipart-formdata:
require('multipart-formdata').parse(req.body, boundary)
//returns [{field, name, data, filename, type}, ...] where data is buffer you can use to save files
As Azure Functions has wrapped http server object in Node.js, and exposes a simple req and context with several functionalities, refer to https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-node#exporting-a-function for details.
And mostly, Azure Functions is designed for triggers and webhooks requests, you can refer to https://learn.microsoft.com/en-us/azure/azure-functions/functions-compare-logic-apps-ms-flow-webjobs for the detailed comparison.
Meanwhile, you can try the answer of Image upload to server in node.js without using express to parse the request body content to file content, and upload to Azure Storage leveraging Azure Storage SDK for node.js, you can install custom node modules via KUDU console. Refer to https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-node#node-version--package-management for more info.
And I suggest you can try to leverage Azure API App in node.js to approach your requiremnet. As it is an expressjs based project, which will be more easier to handle upload files.
Any further concern, please feel free to let me know.
I have good experiences with the new azure-function-multipart package. Example code might look like this:
const {
default: parseMultipartFormData,
} = require("#anzp/azure-function-multipart");
module.exports = async function (context, req) {
const { fields, files } = await parseMultipartFormData(req);
console.log("fields", fields)
console.log("files", files)
};
See docs for more details.
You can try to use this adapter for functions and express, it may allow you to successfully use the multi-part middleware you want: https://github.com/yvele/azure-function-express
As a less desirable option, you can parse the body yourself, all the multi-part data will be available in req.body and will look something like this:
------WebKitFormBoundarymQMaH4AksAbC8HRW
Content-Disposition: form-data; name="key"
value
------WebKitFormBoundarymQMaH4AksAbC8HRW
Content-Disposition: form-data; name=""
------WebKitFormBoundarymQMaH4AksAbC8HRW--
I do think it's a good idea to support httpserver / express better in order to enable this extensibility.
I'm using Context.io's Node.js client library to get the body of emails from my account which is done in my code below.
Once I have that data, I am confused as to how I would get them over to the front-end. I'm new to the whole MEAN stack, and from my research of the basics, I have gathered that with Node, you can make the http calls, parse the json response and then write it to the server, but it seems as if I would have to make an API to then be able to call it from Angular and display it how I wish. I know that with other back-end languages like PHP, you can just write the code within the html, and not need a middle structure to get the info from PHP to the front-end. Is there an easier way than writing my own API in Node after having already made an API request to Context.io?
ctxioClient.accounts(ID).messages().get({limit:10}, function ( err, response) {
if(err) throw err;
console.log("getting responses...");
var messages = response.body;
console.log("message id is " );
console.log(messages.body);
You should implement the backend in JSON using something like res.json and make AJAX requests via Angular $http or something similar.
How to Handle a Coinbase Callback in NodeJS to Recieve Instant Bit Coin Payment Notifications ?
Please I need example.
Note : I'm using SailsJS MVC Framework.
OK, based on your comment, I will give it a go.
I am assuming you have (or will have) an ExpressJs app.
UPDATE Sorry, I just noticed you're using sailsjs. The below should still be valid but you'll need to adapt it to work with the sails routing engine.
In your app, you need to define the post route:
// the app variable is the express js server
// name the route better than this...
app.post('/coinbase', function(req, res){
var data = req.body;
var orderId = data.order.id;
// etc...
});
I'm quite new to AngularJS and NodeJS. I'm trying to develop an app using MEAN stack. I just looked through the sample code in the mean.io boilerplate. I created my own app referring the sample app. I'm trying to submit the AngularJS front end and expecting it to call NodeJs server side but it isn't working. I think service.js is messing up something. Here is the service code of sample app. Can any one explain what this code does with respect to Angular client side and NodeJS Server side.
'use strict';
//Articles service used for articles REST endpoint
angular.module('mean.articles').factory('Articles', ['$resource', function($resource) {
return $resource('articles/:articleId', {
articleId: '#_id'
}, {
update: {
method: 'PUT'
}
});
}]);
It creates a new factory in angular called Articles. The Articles factory has the $resource service injected. The $resource object is used to setup an object for communicating with a RESTful service, in this case "articles/:articleId" the articleId will be pulled from the _id of the resource objects that are returned from queries using this $resource. When you call to update on one of the resources it will use the PUT HTTP Verb.
By itself this just defines the factory but doesn't actually make any calls you would need to inject this and use it somewhere like Articles.query();
From the docs
If the parameter value is prefixed with # then the value of that
parameter is extracted from the data object (useful for non-GET
operations).
I am trying to build a test app for learning Node.js. I came from wordpress background and Apache has setup most of backend logics for me. But now, I have to build my own. I have a question about how to serve JSON files from server side to client side. What is the workflow -- Backbone.js handle all client side Data manipulation, send/save/get/fetch from couchDB, serve JSON object from NODE.js backend?
I am using Express Microframework for building HTTP server, installed the Cradle middleware for access CouchDB NoSQL database. I successfully posted the data from Client side HTML (Jade template engine) to the CouchDB Database/Document and able to retrieve those data back from Server through Cradle middleware. Things work out great. But it was all done by Backend.
I want to use Backbone.js for my client side Javascript. Backbone.js is looking for JSON object which send back from the HTTP server. Cradle Middleware is able to create JSON object but only send them directly to the Jade Template, I could use Jade syntax for loop to iterate over the data object but it still not meet what I want for Backbone.js handle all the data entry. I realize that I need to get JSON obj via ajax ( either a file generated by HTTP then send back to the client OR send straight object to the client ). Cradle Middleware could not do that.
I did more research on this questions. I tried CouchApp, it does what I need. Using the Backbone.js to handling all the data, send/save/fetch data from CouchDB database. But it is a running in CouchApp, it is not an Express Node.js workflow. ( Maybe I am wrong or just do not how it work )
I tried backbone-couchdb.js. I read through the Details and still do not know it is going to help me to get what I want. ( Maybe need more tutorial or code example ). I am still thinking that I need a Backbone CouchDB driver to connect those two and somehow serving them by NODE.js backend.
Is there anybody who could tell me about how JSON file is being served by Node.js, how backbone.js interact with data save/fetch/get from CouchDB? What is the best practice / workflow? Other good resources, code examples, useful tools?
Cradle Middleware is able to create JSON object but only send them directly to the Jade Template
This is incorrect. You can just send the json back without rendering a template.
function(req, res, next){
db.view('user/byUsername', { key: 'luke' }, function (err, doc) {
res.send(doc); // or res.json(doc);
});
}