Handling multipart/formdata and json payloads with Express? - json

I have an express server that handles json payloads (using body-parser). It's a pretty standard setup:
const app = express();
...
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
...
app.post('/api/v1/login', usersController.login);
...etc
But now I have one query - a hook from an outside service - that's submitting data to me as multipart/formdata. How do I deal with those? Do I have to rejigger my entire setup?
Thanks.

I use connect-multiparty package.
An option could be like this (more specific):
var multipart = require('connect-multiparty');
app.post('/api/v1/login', multipart(), function(req, resp) {
console.log(req.files); // in req.files are the files
});
Or just:
var multipart = require('connect-multiparty');
app.use(multipart());

Related

ReactJs and NodeJs JSON parser issue. app.use(bodyParser.json) seems not working

I'm a beginner of ReactJs, NodeJs, express, etc and all the Javascript things. I'm trying the following code sample to learn the basics.
My issue is when I commented out the following line
app.use(bodyParser.json);
I can see the returning data. But if uncomment it back data will not appear. Anyway, the returning data is coming as an object array as below.
[object Object],[object Object],[object Object],[object Object]
How can parse the JSON to see the actual data?
Do I really need to specify following two lines to get JSON data? if so, how to do it?
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json);
Following is the full code
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
var Client = require('node-rest-client').Client;
var client = new Client();
const app = express();
app.use(bodyParser.urlencoded({extended:true}));
app.use(cors());
app.use(bodyParser.json);
app.post('/api',(req,res)=>{
client.get("https://url", function (data, response) {
// parsed response body as js object
console.log("DATA : "+data);
res.json({msg:true,data:data});
// raw response
//console.log("RESPONSE: "+response);
});
});
app.listen(3001,()=>{
console.log("listning to port 3001");
})
Here is the dependency versions as in the package.json file
"dependencies": {
"body-parser": "^1.18.2",
"cors": "^2.8.4",
"express": "^4.16.2",
"node-rest-client": "^3.1.0"
}
Highly appreciate your feedback
you can use it like this my friend
app.post('/api',(req,res)=>{
client.get("https://url", function (data, response) {
console.log(req.body);
res.json({msg:true,data:req.body});
});
As it says in the documentation
You need to use it like this
// parse application/json
app.use(bodyParser.json())
You are using
app.use(bodyParser.json)
Where you have missed ()

Proxy webpack-dev-server based on request payload to return json file

So I've searched and I think a saw the entire internet but no solution regarding the issue I encounter.
I have multiple http request which I want to mock. All request have the same url but deviate based on the requestPayload which contain a graphQl query. Based on this query I want to return a specific json file. All proxy settings I have found can handle parameters but do not handle responses based on requestPayload.
Have you taken a look over this functionality?
https://webpack.js.org/configuration/dev-server/#devserver-before
as far as webpack-dev-server is an instance of express app you are able to setup it in the before/after hooks. Hooks get app (server) instance as a first argument.
so for your case your webpack development config would look like:
module.exports = {
//...
devServer: {
before: function(app) {
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.get('/some/path/graphql', function(req, res) {
var query = req.body;
// ...your custom logic of
// specific query handling goes here
if (condition(query)) {
res.json({ mockedResponse: 'foo' });
} else {
res.json({ mockedResponse: 'bar' });
}
});
}
}
};
UPD: keep in mind if you're using proxy config for devServer you might want to use after hook instead of before to let your requests be proxified if needed.

Serve static .json file in Nodejs with expressjs and serve-static

I Have the following code:
...
var servceStatic = require("serve-static");
var app = express();
app.use(express.compress());
app.use(servceStatic('static'));
...
Somehow it manages to serve all kind of files except those that end with ".json". Why is this?
you don´t need this module serve-static, because it is build in in express:
create a public folder and than just add this line to your code after your instantiation of express:
var path = require('path');
app.use(express.static(path.join(__dirname, 'public')));
This should hand out all your files including the JSON files.
serve-static#index: By default this module will send “index.html”
files in response to a request on a directory. To disable this set
false or to supply a new index pass a string or an array in preferred
order.
var path = require('path');
app.use(express.static(path.join(__dirname, 'public', {
'index': ['index.json', 'index.html', 'index.htm'],
}));

How can I access my couchdb from my node server using REST/JSON/GET/POST?

I'm trying to access my couchdb from a node.js server.
I've followed the nodejs tutorial, and have set up this simple nodejs server:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(80, "127.0.0.1");
console.log('Server running at http://127.0.0.1:80/');
I would like to make RESTful http and POST requests to the nodejs server. The nodejs server should then be able to make GET/POST request to the Couchdb, which responds with JSON objects.
How might I do this?
First of all I am the author of nano and will use it in this response.
Here go some simple instructions to get started with node.js and CouchDb.
mkdir test && cd test
npm install nano
npm install express
If you have couchdb installed, great. If you don't you will either need to install it setup a instance online at iriscouch.com
Now create a new file called index.js. Inside place the following code:
var express = require('express')
, nano = require('nano')('http://localhost:5984')
, app = module.exports = express.createServer()
, db_name = "my_couch"
, db = nano.use(db_name);
app.get("/", function(request,response) {
nano.db.create(db_name, function (error, body, headers) {
if(error) { return response.send(error.message, error['status-code']); }
db.insert({foo: true}, "foo", function (error2, body2, headers2) {
if(error2) { return response.send(error2.message, error2['status-code']); }
response.send("Insert ok!", 200);
});
});
});
app.listen(3333);
console.log("server is running. check expressjs.org for more cool tricks");
If you setup a username and password for your CouchDB you need to include it in the url. In the following line I added admin:admin# to the url to exemplify
, nano = require('nano')('http://admin:admin#localhost:5984')
The problem with this script is that it tries to create a database every time you do a request. This will fail as soon as you create it for the first time. Ideally you want to remove the create database from the script so it runs forever:
var express = require('express')
, db = require('nano')('http://localhost:5984/my_couch')
, app = module.exports = express.createServer()
;
app.get("/", function(request,response) {
db.get("foo", function (error, body, headers) {
if(error) { return response.send(error.message, error['status-code']); }
response.send(body, 200);
});
});
});
app.listen(3333);
console.log("server is running. check expressjs.org for more cool tricks");
You can now either manually create, or even do it programmatically. If you are curious on how you would achieve this you can read this article I wrote a while back Nano - Minimalistic CouchDB for node.js.
For more info refer to expressjs and nano. Hope this helps!
I have a module (node-couchdb-api) I've written for this exact purpose. It has no ORM or other features like that, it's just a simple wrapper for the HTTP API that CouchDB offers. It even follows the conventions established by Node.JS for async callbacks, making your code that much more consistent all-around. :)
You can use node.js module such as Cradle to work with CouchDB.
Here is a list of available Node.JS modules: https://github.com/joyent/node/wiki/modules
Just make HTTP requests. I would recommend request
Here's an example from my code
request({
"uri": this._base_url + "/" + user._id,
"json": user,
"method": "PUT"
}, this._error(cb));
Here's another example from my code
// save document
"save": function _save(post, cb) {
// doc changed so empty it from cache
delete this._cache[post.id];
// PUT document in couch
request({
"uri": this._base_url + "/" + post._id,
"json": post,
"method": "PUT"
}, this._error(function _savePost(err, res, body) {
if (body) {
body.id = post.id;
body.title = post.title;
}
cb(err, res, body);
}));
}

How to add proxy to Node / Express site?

My site is running on Node and using the Express framework.
My goal is to gather data from the Yahoo Placefinder api. It does not support JSONP, so I need to send my JQuery.getJSON request to my own proxy. My proxy would then send an http request to the Placefinder api, and echo the response.
If I were using php instead of Node, I would just make a new php file that includes a curl request to the placefinder api and echo the response.
But, I am using Node and I'm not sure where to start.
And, I'm using the Express framework.
My Questions are:
Where would the proxy fit within the Express framework? The public folder?
Where can I find some info on how to code a proxy in Node?
Will I need to modify the configuration of my Rackspace cloud (ubuntu) server in order for this to be possible?
See node-http-proxy. It should be better than implementing your own proxy.
Express lets you add middlewares as arguments when you do express.createServer(). Or, you can add them afterwards by using .use(proxy).
I don't think so.
To give an example (untested code):
var httpProxy = require('http-proxy'), express = require('express');
var yahooProxy = httpProxy.createServer(80, 'yahoo.com');
var app = express.createServer();
app.configure(function () {
app.use('/yahoo', yahooProxy);
});
...
Here's another example with 1.0.X that demonstrates header injection.
var express = require( 'express' );
var proxy = require( 'http-proxy' ).createProxyServer;
var app = express();
app.configure(function() {
// Inject some request headers here before we proxy...
app.use( function( req, res, next ) {
req.headers[ 'x-my-header' ] = 'blah blah';
next();
});
// Proxy based on path...
app.use( '/stack', proxy({ target: 'http://stackoverflow.com'} ).web );
app.use( '/yahoo', proxy({ target: 'http://yahoo.com'} ).web );
app.use( function( req, res ) {
res.send({ ok: false, message: 'Not much here.' })
});
}).listen( 3000 );
You can just add another route to your express app, perhaps at /api/yahoo/....
This view function will then make a call to the Yahoo API, probably using: http://nodejs.org/docs/v0.4.9/api/http.html#http.request, and then when that request finishes you simple return the result as JSON.
However, keep in mind that your proxy is public and that anyone can make requests through it. I would suggest some basic authorization. A generated value which you provide to the page making the request should work.
Using http-proxy 1.0 with express:
var httpProxy = require('http-proxy');
var apiProxy = httProxy.createProxyServer();
app.get("/api/*", function(req, res){
apiProxy.web(req, res, { target: 'http://google.com:80' });
});
Nowadays this seems to be the easiest solution to add a proxy to Express:
https://www.npmjs.org/package/proxy-middleware