Get buffer from post body in Expressjs - javascript

I am making an express application that handles post data. Because the request body could be any content type and/or binary, I would like req.body to be a Buffer. So what should I use to get a Buffer that represents the request body? Here is my code:
import express from "express";
const app = express();
app.get("/", (req, res) => {
// Get request body as buffer
// Do something with the buffer
});

body-parser can help achieve this, code example would be as,
import express from 'express';
const bodyParser = require('body-parser');
const app = express();
const options = {
type: 'application/octet-stream',
};
app.use(bodyParser.raw(options));
app.get('/', (req, res) => {
const bufferObject = req.body; // Get request body as buffer
// Do something with the buffer
});
See more details about Raw body parser and default options needs to be supplied - bodyParser.raw([options])

Related

Nodejs Express req.body is empty and header null

I am working on retrieving a post request body so that i can add the arguments in the body to my database.
At first I was getting an error SyntaxError: Unexpected token ' in JSON at position 0 at JSON.parse (<anonymous>) but i added this line applctn.use(express.urlencoded({ extended: true })); // to support URL-encoded bodies and now i get an empty body.
My code looks like this :
const express = require("express");
const moment = require("moment");
const db = require("./dbconnection.js"); //reference of dbconnection.js
var bodyParser = require("body-parser");
const applctn = express();
applctn.use(bodyParser.urlencoded({extended: true}));
applctn.post("/hl7_message", function(req, res) {
var jsonObj = JSON.stringify(req.body);
console.log(req);
When i add ```app.use(bodyParser.json()); // to support JSON-encoded bodies
```SyntaxError: Unexpected token ' in JSON at position 0 at JSON.parse (<anonymous>)
Any advise /tips on how i can retrieve the body contents will be appreciated.
my response
You forgot to add applctn.use(bodyParser.json()). Here is the solution :
const express = require("express");
const moment = require("moment");
const db = require("./dbconnection.js"); //reference of dbconnection.js
var bodyParser = require("body-parser");
const applctn = express();
applctn.use(bodyParser.json());
applctn.use(bodyParser.urlencoded({extended: true}));
applctn.post("/hl7_message", function(req, res) {
console.log(req.body);
res.send({code:200,message:"success"})
})
applctn.listen(3000,function(){
console.log("running");
});

express.js get method cannot get req.body value

I use vue3, vuex, express.js and mysql. In the below router get method, I call "console.log(req.body)" and shows "[object Object]", and I call "console.log(req.body.userid)" and shows "undefined".
router.get('/',async function(req,res){
const userId = req.body.userid;
console.log("req body is: "+req.body);
console.log("req.body.userid is: "+req.body.userid);
.....
}
In the below method, I pass userid value as a json object. I call "console.log("post userid: "+userinfo.userid);" and shows the the right value "1";
async getsp(){
var userinfo = JSON.parse(localStorage.getItem('user'));
console.log("post userid: "+userinfo.userid);
var userid = userinfo.userid;
var obj = {userid};
return await axios.get('//localhost:8081/getSp',obj)
.then(...)
},
And in the main router file I used body-parser, the file context is below:
require("dotenv").config();
const express = require('express');
const bodyParser = require('body-parser');
var cors = require('cors');
const signup = require('./userSignUp');
const login = require('./userLogin');
const createEvsp = require('./createEvsp');
const getSp = require('./getSp');
//const createFile = require('./createFile');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json())
app.use(cors())
app.use(express.json());
app.use(
express.urlencoded({
extended: true
})
);
app.use("/signup",signup);
app.use("/dologin",login);
app.use("/createEvsp",createEvsp);
app.use("/getSp",getSp);
//app.use("/createFile",createFile);
app.listen(8081,function () {
console.log('Server running at 8081 port');
});
The problem was an HTTP method understanding and how express works
To solve it it was needed to use the express middleware /:userid for accessing to the parameter using req.params.userid
According to the http standards for sending the data we generally use POST request.
There is a good answer in stack here Information about Get HTTP Request
Sayf-Eddine

Express js bodyparser post req.body not working?

I try to build an api with express js post request. I use body-parser for req.body . But after sending post request i couldn't get any message still loading then show timeout. where is my problem please take a look my code.
I am testing it from postman and use on header content-type application/json.
const express = require('express');
const bodyParser = require('body-parser');
const config = require('./config/config.js').get(process.env.NODE_ENV);
const mongoose = require('mongoose');
const app = express();
mongoose.connect(config.DATABASE)
const {Book} = require('./models/book')
app.use(bodyParser.json())
// Post Book
app.post('api/book', (req,res)=>{
let book = new Book(req.body)
book.save((err, doc)=>{
if(err) return res.status(400).send(err);
res.status(200).json({
post:true,
bookId: doc._id
})
})
})
Now error show- cannot post /api/book
but when i try with this below code its working--
const book = new Book({ name: 'Zildjian' });
book.save().then(() => console.log('data save'));
Change your route from api/book to /api/book - add a leading /.
Also, it looks like it might be timing out as it can't get passed your cookie-parser middleware.
You have passed the function:
app.use(cookieParser)
...but you need to invoke it:
app.use(cookieParser())
You will also need to import it:
const cookieParser = require('cookie-parser')
...or just remove it completely if you don't need it.
I hope this helps.

Express Body Parser with both JSON and binary data passing capability

In my express app router, I've routes for accepting POST request of JSON data as well as binary data. The problem is when I use body parser for passing JSON data, it also considers the binary data as JSON and gives error while POSTing binary data. i.e. when I use:
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));
And When I remove this, It only works for binary data. Following is my route for POSTing binary file.
router.post('/file', function (req, res) {
var gridfs = app.get('gridfs');
var writeStream = gridfs.createWriteStream({
filename: 'file_name_here'
});
writeStream.on('close', function (file) {
res.send(`File has been uploaded ${file._id}`);
});
req.pipe(writeStream);
});
I've also tried moving this file route to other router. In that case, when I don't set anything regarding body parser, it still gives the same error.
One fix that works correctly is placing this file route in my main app.js prior to setting body parser. But I think this would not be good approach. I want these routes to be in separate files.
So what I'm missing here? Any alternatives will also be appreciated.
EDIT
As per the answer, I've first separated out my routers which requires body parsing and which do not. Also removed the bodu parser from my main app.use() Now in the router in which, I need body parser, I've added those 2 lines. But the behavior is same.
When I add those 2 lines, only JSON reqquest works and when I remove, only binary POST req. works.
Here is my updated code:
app.js
const express = require('express');
const app = module.exports = express();
const bodyParser = require('body-parser');
const port = 8080;
// //parsing incoming requests using body-parser middlewares
// app.use(bodyParser.json());
// app.use(bodyParser.urlencoded({ extended: false}));
//adding routes
app.use(require('./routes/additionRouter'));
app.use(require('./routes/mediaRouter'));
//catch 404 file not found here
app.use((req, res, next) => {
const err = new Error('Page Not Found');
err.status = 404;
next(err);
});
//Error Handler
app.use((err, req, res, next) => {
res.status(err.status || 500);
res.send(err.message);
});
app.listen(port, () => {console.log('Server listening on port: ' + port)});
additionRouter.js
const express = require('express');
const router = express.Router();
var exported = require('../config/dbConnection');
const bodyParser = require('body-parser');
// parsing incoming requests using body-parser middlewares
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({ extended: false}));
//Endpoint for adding new challenge
router.post('/endpoint1', (req, res, next) => {
});
module.exports = router;
and mediaRouter.js
const express = require('express');
const mediaRouter = express.Router();
const exported = require('../config/dbConnection');
exported.cb((gridfs) => {
//For adding media files to database named 'mediadb'
//POST http://localhost:8080/file
mediaRouter.post('/file', function (req, res) {
// var gridfs = app.get('gridfs');
var writeStream = gridfs.createWriteStream({
filename: 'file_name_here'
});
writeStream.on('close', function (file) {
res.send(`File has been uploaded ${file._id}`);
});
req.pipe(writeStream);
});
//GET http://localhost:8080/file/[mongo_id_of_file_here]
mediaRouter.get('/file/:fileId', function (req, res) {
// var gridfs = app.get('gridfs');
gridfs.createReadStream({
_id: req.params.fileId // or provide filename: 'file_name_here'
}).pipe(res);
});
});
module.exports = mediaRouter;
By specifying
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));
your entire app uses the body parser middleware. You could create another middleware to handle whether or not the body parser is used. For example:
const bodyParse = bodyParser.json();
app.use((req, res, next) => {
if(req.originalUrl == "restOfUrl/file") next();
else bodyParse(req, res, next);
});

Graphql: Must provide query string

I have a simple express graphql server:
const schema = require('./schema');
const express = require('express');
const graphqlHTTP = require('express-graphql');
const cors = require('cors')
const bodyParser = require('body-parser');
const app = express();
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/graphql', graphqlHTTP(req => {
return ({
schema,
pretty: true,
})
}));
const server = app.listen(9000, err => {
if (err) { return err; }
console.log(`GraphQL server running on http://localhost:${9000}/graphql`);
});
And my request looks like:
Any help?
(Please don't close it as duplicate because the other post does not provide enough info on how the user solved it)
You need to specify application/json in your Content-Type header -- you currently have text/plain. You've included the body parser middleware on the server, but it relies on that header in your request to know when it needs to actually parse the response into JSON.

Categories

Resources