How to consume JSON in Express JS? - node.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())

Related

Unable to receive files in request using express-fileupload

I use a REST client to test my app (Insomnia and postman). My app literally does nothing:
const express = require('express');
const app = express();
const fileUpload = require('express-fileupload');
app.use(express.json())
app.use(fileUpload());
app.post('/', fileUpload(), function(req, res) {
console.log(req.files)
res.send('a')
});
const PORT = 9999;
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}...`);
});
Whenever I try to upload a file to this service req.files is undefined. I took this code from express docs page and from a few stackoverflow questions and it just doesn't work for me. Content-length is good (40k seems right)
Content-type is auto set by my REST client. Do I have to change this?
I tried simply printing whole request object and body is empty and files is not even present there
So for anyone wondering. fileupload requires form-data Content-type. Moreover, it also requires a file to have a "key" within this form-data. It's a shame documentation fails to mention this.
Just do one thing: remove file fileUpload() from post endpoint and check, find below code for your reference.
app.post('/', function(req, res) {
console.log(req.files)
res.send('a')
});

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

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')

Postman send strange response for raw JSON post (node js)

I'm trying to do a POST request using raw json.
In the Body tab I have "raw" selected with this body:
{
"name": "book"
}
On the Node js side I'm doing res.send(JSON.stringify(req.body))
router.post('/', (req, res, next) => {
res.send(JSON.stringify(req.body));
}
And in POSTMAN response I receive:
{"{\n\"name\": \"book\"\n}":""}
When expected something like
{"name":"book"}
Have no idea - where could be a reason for it?
You'll need to use the Express JSON body parser, install using
npm install body-parser;
Then:
const bodyParser = require('body-parser');
app.use(bodyParser.json());
Once you do this, the JSON data will be parsed correctly and when you send it back it will render correctly.
Also make sure you have your Content-Type header set to "application/json" in your Postman request (go to "Headers" and add a new "Content-Type" header with value "application/json")
Here's a simple express app that will echo any JSON POST:
const express = require("express");
const port = 3000;
const app = express();
const bodyParser = require('body-parser')
app.use(bodyParser.json());
app.post('/', (req, res, next) => {
console.log("Body: ", req.body);
res.send(JSON.stringify(req.body));
})
app.listen(port);
console.log(`Serving at http://localhost:${port}`);
If you're on Express v4.16.0 onwards, try to add this line before app.listen():
app.use(express.json());
This is a built-in middleware function in Express. It parses incoming requests with JSON payloads and is based on body-parser.
Looks to me like its not a fault of Postman, but your NodeJS service is applying JSON.stringify twice?
Can you log the response type from the server to console to check whether its already json content or not?
try with hard coded json response and then with dynamic variable
res.json({"name":"book"});

app.post() method is not working in nodejs

I am new to MEAN Stack and have been developing some applications on Mean stack.But I am stuck with my app.post() method .The browser's console gives a 405 error saying that the method is not allowed.Please help me.
Here;s my code for server file in javascript
var app =express();
var mongoose =require('mongoose');
var bodyParser =require('body-parser');
var urlencodedparser=app.use(bodyParser.urlencoded({extended:false}));
var jsonParser = bodyParser.json()
app.get('/',function(request,response){
response.sendFile(__dirname+'/clients/views/index.html');
});
app.post('/api/meetups',jsonParser,function(req,res){
console.log(req.body);
});
var port=process.env.PORT || 3000;
app.listen(port,function(){
console.log('Listening to the server at port '+port);
});
Based on the Application.post() Express documentation, I think you probably want to change the first line of your post listener from:
app.post('/api/meetups',jsonParser,function(req,res){
console.log(req.body);
});
To this:
app.post('/api/meetups',function(req,res){
console.log(req.body);
});
I don't think it takes the additional parameter you specified related to JSON parsing. If you need to parse JSON you may want to look into using body-parser with middleware like this (which you would put ABOVE the post listener):
var bodyParser = require('body-parser');
app.use(bodyParser.json());
Good luck!

Resources