Sending form data to an server using multer - node.js

I'm having some trouble sending form data to my Node.js server. I'm closely following the examples in the readme, but the result is either an empty object or undefined.
This is my server code:
var express = require('express')
var app = express()
var multer = require('multer')
var upload = multer()
app.post('/', upload.array(), function (req, res, next) {
console.log(req.body)
res.send("Hello from the server!")
})
app.listen(3000)
I'm testing this by running the following in the Chrome console:
var xml = new XMLHttpRequest()
xml.open("POST", "/")
var fd = new FormData()
fd.append("foo", "bar")
xml.setRequestHeader("content-type", "multipart/form-data; boundary=200")
xml.send(fd)
I don't know how to get the correct boundary for the setRequestHeader call, so I just put 200. When I send this, the server prints {}. It prints undefined without the setRequestHeader call. xml.responseText is the expected string Hello from the server!.

Related

Node.js - how to use a raw request body using Express

so I was making a RESTful API and I wanted to be able to receive raw json data (so I can use my api for mobile too), then from there save the data into my database (mongoDB).
But you see, there is this problem which I can't seem to fix and its that I'm not able to use the raw data as a json.
The code is simple
const express = require('express')
const bodyParser = require('body-parser')
const app = express();
app.use(bodyParser.raw({inflate:true, limit: '100kb', type: 'application/json'});
app.post('/post', function(req, res){
res.send(parse.JSON(req.body));
//to convert it to json but this doesn't seem to work
})
PS. I'm using postman to send the request as raw format
const express = require('express')
const bodyParser = require('body-parser')
const app = express();
app.use(bodyParser.raw({inflate:true, limit: '100kb', type: 'application/json'});
app.post('/post', function(req, res){
res.send(JSON.parse(req.body));
})
inside the res.send you have to use JSON.parse() instead of parse.JSON() which will throw an error as it is not correct
if you want to read more about JSON.parse you can visit mdn docs

Cannot extract data from post request in node

I am sending a post request using axios in react to a nodejs backend and mysql database.
At the server side when I log req.body, it is undefined
and this is the params and query part when I log the request on server side:
params: {},
query: {},
This is inside the handlelogin method in react:
handleLogin=(event)=>
{event.preventDefault();
let formfields={...this.state.formfields};
axios.post('http://localhost:7000/api/login',{formfields
})
.then(res=>
{
console.log("response receieved");
})
.catch(err=>
{
console.log(err);
});
};
This is the node script( inside routes):
const express = require('express');
const exp = express();
const bodyParser = require('body-parser');
exp.use(bodyParser.urlencoded({extended:false}));
exp.use(bodyParser.json());
const router = express.Router();
router.post('/api/login',(req,res,next)=>{
console.log('Inside login-serverside');
console.log(req);
});
module.exports = router;
I want to submit forms and pdf files(later) but I cannot access them on the server side.I can acces request.parameters when I make a get request.What is the issue here?
What are body,params and query used for, respectively and what is the difference?
I had not included body parser in my main server.js file
const bodyParser = require('body-parser');
exp.use(bodyParser.urlencoded({extended:false}));
After including this, it's working. I can now successfully use request.body and access the parameters passed in axios.post .
Though I am still confused about the use of params,query,data and body respectively.

response object is undefined, of post method function

this is simple demo, making http post request and tries the log request object;
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
var router = express.Router();
app.use(router)
app.use(bodyParser.json())
foo=(req, res)=>{
console.log(req.body)
res.send('Request Handled Here!')
}
router.route('/').post(foo)
app.listen(3300, '127.0.0.1', (req, res)=>{
console.log("Express listening!!!!")
});
I can see data "Request Handled Here" message but return data is undefined always in the console, I couldn't figure why "req" object is undefined out.
Edited: I am using postman to test api, content-type:application/json and there is {message:"hello world!"} dummy data in Body section
Edited2: it seems my only issue there is no "body" attribute in request context, it retrieves all req header but I just want to get posted data, many samples on net contains req.body section whats wrong here?
The problem in middleware declaration order. router must be added after body-parser:
var app = express()
var router = express.Router();
app.use(bodyParser.json());
app.use(router);

Context object is empty while receiving POST request , in Koa?

I am new in Koa and I am creating a demo app. I want to create an API to handle POST request, But when I console.log(ctx); then there is nothing in ctx in indexRouter.js, the console only printing empty object like {}.
I don't know why this is happening. Please anyone suggest me where I am doing wrong?
And please help me to get the request.body by POST Method.
serverKoa.js:
var koa = require('koa');
var router = require('koa-router');
var app = new koa();
var route = router(); //Instantiate the router
app.use(route.routes()); //Use the routes defined using the router
const index = require('./router/indexRouter')(route);
app.listen(3005 ,function(){
console.log("\n\nKoa server is running on port: 3005");
});
indexRouter.js:
var indexController=require('../controller/indexController');
module.exports = function (route) {
route.post('/postnew',async ( ctx, next) => {
console.log(ctx); // here printing {}
});
}
and my request object ( by postman ) is:
Method: POST,
url:http://localhost:3005/postnew
body:{
"firstName":"viki",
"lastName":"Kumar",
"userName":"vk12kq14",
"password":"098765432"
}
content-type:application/json
It looks like your code has two issues:
you're not using the "next" version of koa-router, which is required if you want to use async/await. You can install it like this:
npm i koa-router#next --save
you're not using koa-bodyparser to parse the request data:
npm i koa-bodyparser --save
To use:
var koa = require('koa');
var router = require('koa-router');
var bodyParser = require('koa-bodyparser');
var app = new koa();
app.use(bodyParser());
...
The parsed body data will be available in your route handlers as ctx.request.body.

How to access the raw body of the request before bodyparser?

I am writing a custom middleware that generates a cryptographic signature of every request (it is very similiar to the authentication mechanism used by AWS API v4). In order for this signature to be correctly generated, I must fetch the entire raw body of the HTTP request.
I am also using BodyParser, which is registered after my custom middleware.
My custom middleware can be represented like this:
// libs/simplifiedSignatureCheckerMiddleware.js
module.exports = function (req, res, next){
// simple and fast hashing stuff
var payload = '';
req.on('data', function(chunk) { payload += chunk }, null);
req.on('end', function(){
// hmac stuff
console.log(payload);
var ok = true; // ...
if(ok)
next();
else
next("Bad")
});
}
This is how I use it on the server.
// simpleServer.js
// BASE SETUP
// =============================================================================
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var jsonStream = require('express-jsonstream');
var nconf = require('nconf');
var https = require('https');
var fs = require('fs');
// load configurations
nconf.argv().env();
nconf.file({file: 'config.json'});
app.use(require('./libs/simplifiedSignatureCheckerMiddleware'));
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(jsonStream());
// ROUTES FOR API
// =============================================================================
var router = express.Router();
router.post('/api/', function (req, res) {
var param1 = req.body.param1 || "";
var param2 = req.body.param2 || "";
res.json({message: 'welcome', one: param1, two: param2 });
});
// REGISTER ROUTES
app.use(router);
// START THE SERVER
// =============================================================================
https.createServer({
key: fs.readFileSync('./key.pem'),
cert: fs.readFileSync('./cert.pem')
}, app).listen(nconf.get('http:port'));
console.log("APIs listening on port " + nconf.get('http:port'));
As you can verify, the raw body is written successfully to the console by the middleware, BUT the request will never be processed by the registered route and the connection hangs forever.
Do you have any clue on how to solve this problem?
Thanks in advance.
Ok, since the only feasible way to solve this problem seems to be by modifying the original source code of bodyParser, I have forked it.
https://github.com/emanuelecasadio/body-parser-rawbody
This fork exposes the raw body of the request as a field named rawBody. As you can see, there is only ONE extra line of code.
You can install it by using npm install body-parser-rawbody.
EDIT
Another option is to use the bodyParser like this, as noted by dougwilson here: https://github.com/expressjs/body-parser/issues/83#issuecomment-80784100
app.use(bodyParser.json({verify:function(req,res,buf){req.rawBody=buf}}))
I haven't personally tried this option and I do not know if it works.

Resources