Unable to see the request body in the console when using Postman - express

Since the last Postman update, I'm unable to get the response data in the console, from the request body that I'm sending to the endpoint.
Here's the code:
let express = require('express');
let app = express();
let bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/', (req, res) => {
console.log(req.body);
res.send('OK');
});
app.listen(8080, () => console.log('App is listening! :)'));
Then I make a POST request using Postman putting data in the Body part, On the log I get "{}".
I have tested with cURL, and it works, that's why I suspect it is a problem with Postman.
Thank you for your time!

Using the code from the question, I am able to see the request body logged out to the console. This is using either the raw > application/json option or the x-www-form-urlencoded option the send the request.
In order to see data from the form-data option in Postman, I needed to add the multer module to the code.
let express = require('express');
let multer = require('multer');
let upload = multer();
let app = express();
let bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/', upload.array(), (req, res) => {
console.log(req.body);
res.send('OK');
});
app.listen(8080, () => console.log('App is listening! :)'));
As you can see from the image below, this is writing the request body to the console.

Related

Can't seem to get req.body in Express when embedded in Zoho Catalyst framework

My Zoho Catalyst framework isn't passing the request.body. Here is the code.
module.exports = (req, res1) => {
const debug = require('debug');
const https = require('https');
const tools = require('./tools.js');
const crypto = require('crypto');
const express = require('express');
const app = express();
app.use(express.json())
app.use(express.urlencoded({ extended: true }));
app.use(express.text());
function getHash(){
var hmac = crypto.createHmac('sha256', apisecretkey);
hmac.update(dataToSign);
return hmac.digest('base64');
};
var url = req.url;
switch (url) {
case '/scanName':
//var s = JSON.stringify(req.body)
console.log(req.body)
console.log(req.get('Accept'))
console.log(req.accepts('application/json'));
res1.write('xx')
res1.end()
break;
case '/':
Here is the output:
undefined
*/*
application/json
I've tried every form of POST from Postman that I can think of, and still nothing.
You have bound the express app variable to recognize the incoming data of the following types JSON, urlencoded and text. But you haven’t used that app variable to get the incoming request so technically it is like you have declared it but never used it. So, your function code couldn’t be able to identify the type of incoming data in the request body. You can modify your code like below:
'use strict';
const debug = require('debug');
const https = require('https');
const tools = require('./tools.js');
const crypto = require('crypto');
const express = require('express');
const app = express();
app.use(express.json());
app.use(express.text());
app.use(express.urlencoded({ extended: true }));
app.post('/scanName',async(req, res) => {
try {
let body = req.body;
console.log(body);
res.status(200).send(body);
} catch (error) {
console.log(error);
res.status(500).send(error);
}
});
module.exports = app;
You have to export the express app variable to make the endpoints accessible. You can check out this tutorial where we have shown an example of how to get and send data in the Catalyst Advanced IO function using Express.js.

Unable to Connect to Backend

Hello i am Trying to connect React-Native with Node.js using Fetch Api i tried many solutions i tried putting my IP address,localhost and 10.0.2.2 but nothing works i dont get any response back but when i change my code a little bit it gives me network failed request error.
React-Native Code:
//Sending Request to Node.js using Fetch API
await fetch("http://10.0.2.2:3000/studentSignup", {
//Setting Method
method:"POST",
//Setting Headers
headers:{
//Setting Content-Type
"Content-Type" : "application/json"
},
//Stringifying the email and password and storing it into body
body:JSON.stringify({
name,
gmail,
password,
retype
})
}).then(res=>{
console.log(res);
}).catch(err=>{
console.log(err);
});
Node.js:
const express = require("express");
const app = express();
app.use("/studentSignup", (req,res,next)=>{
console.log("ok");
});
app.listen(3000);
lots of Mistakes
Full source code
var express = require('express')
var cors = require('cors')
var app = express()
var bodyParser = require('body-parser')
// create application/json parser
var jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.use(jsonParser)
app.use(urlencodedParser)
app.use(cors())
app.post("/studentSignup", (req,res,next)=>{
console.log("ok");
});
app.listen(3000);
First of all, it's app.post not app.use
app.post("/studentSignup", (req,res,next)=>{
console.log("ok");
});
This might me due to cors
You can use this npm package to encounter this error cors
install cors in server folder
npm i cors --save
Usage
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.post("/studentSignup", (req,res,next)=>{
console.log("ok");
});
app.listen(3000);
Use body parser to handle incoming data from frontend
install body-parser in server folder
npm i body-parser --save
Usage
var express = require('express')
var cors = require('cors')
var app = express()
var bodyParser = require('body-parser')
// create application/json parser
var jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.use(jsonParser)
app.use(urlencodedParser)
app.use(cors())
app.post("/studentSignup", (req,res,next)=>{
console.log("ok");
});
app.listen(3000);
So i was debugging and i thought that i have 2 ip's first one was Internet's ip and the second one was mine pc's ip and i was using internet's ip instead of my machine's ip so i changed the ip and that worked smoothly.

BodyParser causes all API requests to hang. Even basic GET requests

As the title says, I simply don't understand what is going on here. Once I include the app.use(bodyParser.json) line, Postman just keeps handing on any request I make. I lost a good portion of the day thinking I messed up my routes.
I narrowed it down to it in this little testing file:
const express = require("express")
const bodyParser = require("body-parser")
const env = require("dotenv");
const app = express()
env.config();
app.use(bodyParser.json);
app.get("/", (req, res) => {
res.status(200).json({
message:"Hello World"
})
});
app.post("/data", (req, res) => {
req.status(200).json({
message: req.body
})
});
app.listen(process.env.PORT, ()=>{
console.log(`Server listening at port ${process.env.PORT}`);
})
Can anyone tell me what is happening and how I can fix it?
You need to call JSON body parser as a function (with brackets):
app.use(bodyParser.json());
There is another bug in the post method "data", You should call status from "res" object:
app.post("/data", (req, res) => {
res.status(200).json({
message: req.body
})
});

AXIOS GET request to instagram not working in prod

I am stuck for a few hours and I can't find an answer.
It's a very simple request that works fine in the browser (it returns a JSON answer), for example :
https://www.instagram.com/eurosportfr/channel/?__a=1
In dev the code:
const express = require('express');
const axios = require('axios');
const cors = require('cors');
const app = express();
app.use(cors());
app.get('/instagram', (req, res) => {
async function getInstagramFeed() {
await axios
.get('https://www.instagram.com/eurosportfr/?__a=1')
.then((response) => {
console.log(response);
res.write(`${JSON.stringify(response.data)}`);
res.end();
})
.catch((err) => {
console.log(err.response);
res.write('<h1>ERROR GRAVE</h1>');
res.write(err.response);
res.end();
});
}
getInstagramFeed();
});
const PORT = process.env.PORT || 8000;
app.listen(PORT, () => console.log(`listening on ${PORT}`));
The result in DEV ENV is JSON data with all what I need.
But in production, it doesn't return me the JSON. Instead it returns me an HTML page...
You can try it here: (I display in the body the result)
https://corsmiddleware.vercel.app/instagram
When I try another api request with another API client, it works just fine in prod, example :
https://corsmiddleware.vercel.app/test
Any idea ??
Thanks
This request now requires authentification. It was working in the past, and it's still actually working here in Morocco where I am, but this solution is not reliable.
The solution is to follow the instructions on facebook :
https://developers.facebook.com/docs/instagram-basic-display-api/

Load post response into existing html page

all:
I have an API call using express and I'm wanting the data to load into an existing paragraph tag on the html page with the form, but currently it loads into a new html page using res.send(). Have checked the express documentation and cannot find anything. Any ideas how I can do this? Here is the code:
const express = require('express');
const app = new express();
const port = 3000;
const request = require('request');
app.use(express.urlencoded({extended: true}));
app.get("/", (req, res) => {
res.sendFile(`${__dirname}/index.html`);
})
app.post("/", (req, res)=>{
let crypto = req.body.crypto;
let fiat = req.body.fiat;
request(`https://apiv2.bitcoinaverage.com/indices/global/ticker/${crypto}${fiat}`, function (error, response, body) {
let data = JSON.parse(body);
let price = data.last;
res.write(`<h1>${price}</h1>`);
});
})
app.listen(port, ()=>{
console.log('Listening on port 3000');
})
Thank you all so much,
Kevin