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

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

Related

How to Send a payload to a firebase OnRequest Function

I have a firebase post function that I am trying to send some data to but the problem I am having is that I the body comes empty. I am using express for the function.
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const express = require("express");
const request = require("request");
const moment = require("moment");
const cors = require("cors");
// const bodyParser = require("body-parser");
admin.initializeApp();
const app = express();
app.use(cors());
app.use(express.json({limit: "10kb"}));
// Mpesa Express
app.post("/express", _accessToken, (req, res) => {
console.log(JSON.stringify("FELOOOOOO", req.body));
console.log(JSON.stringify("felix"));
res.status(200).json(req.body);
});
exports.main = functions.https.onRequest(app);
The functions run but when I log the req.body it comes empty. I have used postman to send the post request but still, the req.body comes empty despite passing in some data. Kindly help solve the error. below is a screenshot of the postman request
You seem to be sending the data correctly but are incorrectly using JSON.stringify(). The object is the first argument, not the second. Make it JSON.stringify(req.body) - that should work.
You can read up more about the function over at MDN docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

Get form data from client to server side NodeJS

I would like send send file from postman to the server, and then send this file to sharepoint using REST API.
When I send my file form-data format body from postman to the server I don't know how to recover it
When I do console.log(file) on server side I have nothing
Can you put your code of the nodeJS server? Without your used code part it is hard to give an answer but you can simply catch the post request as below.
You should use body-parser to receive your data.
run npm install body-parser
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const app = express()
app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.post('/test', (req, res) => {
console.log(req.body.file)
}
app.listen(5000,()=>{
console.log("Running on port: "+5000)
})
Its working using multer
const multer = require('multer')

How to consume JSON in Express JS?

In very new to express js. I just wrote a simple program to send JSON request through postman and get the response.
Why I can't get any response? it always says could not get any response. I go through several tutorials and could not figure out what exact missing here?. Here is my code.
const express = require('express');
const app = express();
app.use(express.json);
app.post('/', (req, res) => {
console.log(req.body);
res.send(req.body);
});
app.listen(3000, () =>{
console.log("Listen in port 30000");
});
I figure out what went wrong. Here
app.use(express.json);
Should be This,
app.use(express.json());
You have to parse your json data inorder to consume it.
check the following code.
install this package.
npm i body-parser
and use it with your express object as below
let bodyParser = require('body-parser')
app.use(bodyParser.json())

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.

Parsing Post Form Data Node.js Express

I am getting form data in this form
'------WebKitFormBoundarysw7YYuBGKjAewMhe\r\nContent-Disposition: form-data; name': '"a"\r\n\r\nb\r\n------WebKitFormBoundarysw7YYuBGKjAewMhe--\r\n
I'm trying to find a middleware that will allow me to access the form data like:
req.body.a // -> 'b'
I've tried
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
Is there a problem with my implementation or am I not using the correct middleware?
The tool that worked was multiparty
app.post('/endpoint', function (req, res) {
var form = new multiparty.Form();
form.parse(req, function(err, fields, files) {
// fields fields fields
});
})
The library which worked for me was express-formidable. Clean, fast and supports multipart requests too.
Here is code from their docs
Install with:
npm install -S express-formidable
Here is sample usage:
const express = require('express');
const formidable = require('express-formidable');
var app = express();
app.use(formidable());
app.post('/upload', (req, res) => {
req.fields; // contains non-file fields
req.files; // contains files
});
The above two answers are correct but now those methods are outdated. multer is a better method to access form data. Install it by the following command: npm install multer
some useful body parsers.
Body-type: parser
form-data: multer
x-www-form-urlencoded: express.urlencoded()
raw: express.raw()
json: express.json()
text: express.text()
-better to use multer.
-But if you want to use bodyParser.urlencoded convert it into URLSearchParams data type
demonstration:-
let fd=new FormData("id_of_form")
let sp=new URLSearchParams()
for(let [k,v]:fd.entries()) sp.append(k,v)
make header 'Content-Type':'application/x-www-form-urlencoded ' and pass sp to body.
-happy coding

Resources