Request urlencoded body is empty in express - node.js

I'm trying to get url parameters in express 4.17.3 using the urlencoded middleware but the body is always empty, I reproducted it to a minimal code:
const express = require("express");
(()=>{
const app = express();
app.use(express.urlencoded());
app.get("/", async(req, res)=>{
console.log(req.body); //always print '{}'
res.send();
});
app.listen(83, ()=>{
console.log("test app listening on port 83");
})
})();
Here's my request
http://localhost:83/?param1=42
What am I doing wrong?

A few things to break down. To answer your question to get params you can use
req.query so your code would be:
app.get('/', async (req, res) => {
console.log(req.query)
res.send()
})
Addressing urlencoded it should be changed from:
app.use(express.urlencoded());
to:
app.use(express.urlencoded({ extended: true }))
good habit to not hard code the port so the line of code:
app.listen(83, ()=>{
console.log("test app listening on port 83");
})
should be:
const PORT = process.env.PORT || 83
app.listen(PORT, () => {
console.log(`test app listening on port ${PORT}`)
})
full working code example:
const express = require('express')
const app = express()
app.use(express.urlencoded({ extended: true }))
const PORT = process.env.PORT || 83
app.get('/', async (req, res) => {
console.log(req.query)
res.send()
})
app.listen(PORT, () => {
console.log(`test app listening on port ${PORT}`)
})
When using express I also like to implement nodemon and if you add this to your package.json:
"dev": "nodemon node index.js"
then in the terminal you can run:
npm run dev
you wont have to restart your server during development changes.

Related

NodeJS api not returning any response

I used this https://medium.com/weekly-webtips/create-and-deploy-your-first-react-web-app-with-a-node-js-backend-ec622e0328d7 to create React Front End and NodeJS backend. On running locally, it worked but I deployed it on Heroku. I didn't receive any response from express server api.
app.get("/test/", (request, response) => {
response.send({"name":"Hello Test!!!"});
});
my proxy setting looks like this
Result in http://localhost:3000/
Hello from the frontend!
Hello Test!!!
Result in https://react-node-js-test.herokuapp.com/
Hello from the frontend!
"proxy": "http://localhost:5000",
server.js
// Import dependencies
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path');
// Create a new express application named 'app'
const app = express();
// Set our backend port to be either an environment variable or port 5000
const port = process.env.PORT || 5000;
// This application level middleware prints incoming requests to the servers console, useful to see incoming requests
app.use((req, res, next) => {
console.log(`Request_Endpoint: ${req.method} ${req.url}`);
next();
});
// Configure the bodyParser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
// Configure the CORs middleware
app.use(cors());
// This middleware informs the express application to serve our compiled React files
if (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'staging') {
app.use(express.static(path.join(__dirname, 'client/build')));
app.get('*', function (req, res) {
res.sendFile(path.join(__dirname, 'client/build', 'index.html'));
});
};
// // Catch any bad requests
// app.get('*', (req, res) => {
// res.status(200).json({
// msg: 'Catch All'
// });
// });
app.get("/test/", (request, response) => {
response.send({"name":"Hello Test!!!"});
});
// Configure our server to listen on the port defiend by our port variable
app.listen(port, () => console.log(`BACK_END_SERVICE_PORT: ${port}`));
Any help would be great
// MOVE THIS BEOFRE get("*")
// Because * will handle all incoming requests
app.get("/test/", (request, response) => {
response.send({"name":"Hello Test!!!"});
});
// This middleware informs the express application to serve our compiled React files
if (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'staging') {
app.use(express.static(path.join(__dirname, 'client/build')));
app.get('*', function (req, res) {
res.sendFile(path.join(__dirname, 'client/build', 'index.html'));
});
};

nodej.js handling of post req.body is not working

I spend so much time looking at this.. I am just following udemy tutorial where instructor used exactly below.. BUT when I run it, req.body is empty EVEN though I am sending it from source(I tried from both nodeman and insomnia). I am just posting { "name":"test" }... and it's not getting the req.body...
I console logged just req and do not see the parm 'body'... Can someone please throw me some light here? SO furstrated
const express = require('express');
const app = express();
const port = 8002;
app.post('/', (req, res) => {
console.log(req.body);
});
app.listen(port, () => {
console.log(`port : ${port}`);
})
Try using body-parser for your req.body.
First install the dependency npm install body-parser and then try executing the below code:
const app = express();
const bodyParser= require('body-parser')
const port = 8002;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.post('/', (req, res) => {
console.log(req.body);
});
app.listen(port, () => {
console.log(`port : ${port}`);
})
For more documentation refer: body-parser-documentation

nodejs express req.body undefined

I write this code and req.body is undefined
I want to get post value in my program
can you help me, please?
const express = require('express')
const app = express()
const port = 3000
const crypto = require('crypto');
function sha1(s) {
return crypto.createHash("sha1")
.update(s)
.digest("hex");
}
app.post("/flag", (req, res) => {
console.log(req.body);
});
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
You body-parser npm package
$ npm i body-parser
var express = require('express')
var bodyParser = require('body-parser')
const app = express()
const port = 3000
const crypto = require('crypto');
var app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
function sha1(s) {
return crypto.createHash("sha1")
.update(s)
.digest("hex");
}
app.post("/flag", (req, res) => {
console.log(req.body);
});
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
Instead of using body parser, Express already providing support for that,
import express from "express";
const app = express();
app.use(express.json());
app.use(express.urlencoded());
This should be given before the Api route

How to parse req.body in node js

I am passing 10.0.0.12 value in axios get from react side to node , When I am trying to print req.body on node side it displays [object,object] how to get value from object?
This How I am sending req:
axios
.get("/ashjg/GetTfsItem",
{BuildNumber:event.target.value[event.target.value.length-1].BuildNumber},{headers: {'Content-Type':'application/json'}},
)
.then(response => {
console.log("responce data"+response.data);
if(response.status==200){
this.setState({TfsItemdata : response.data});
}else{
this.setState({errorMessage:"Data Not Available "})
}
})
.catch(error => {
this.setState({errorMessage:"Data Not Available for Crash Id "})
});
}
Node Js Side :
router.get("/GetTfsItem",function(req,res,next){
console.dir( "Inside GetTfsItem " + Jreq.body );
}
Try using body-parser like this:
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.use(function (req, res) {
res.setHeader('Content-Type', 'text/plain')
res.write('you posted:\n')
res.end(JSON.stringify(req.body, null, 2))
})
Remember you need to install body-parser:
npm i body-parser
In case if you are using express.js then you can do it like this:
const express = require('express')
const app = express()
const port = 3000
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
app.post('/handle',function(request,response){
var query1=request.body.var1;
var query2=request.body.var2;
});

What am I doing incorrectly with my https request?

I'm learning how to build a RESTful api with Node and Express, and I am having an issue with this https request. I am trying to make a GET request to Scryfall's api (documentation here: https://scryfall.com/docs/api), but whenever I run my server and check the browser I get a message stating
"localhost didn’t send any data. ERR_EMPTY_RESPONSE".
As I'm new to using Node and Express, I'm not really sure what I am doing wrong. Here is the code for my server.js and app.js files.
//server.js
const https = require('https');
const app = require('./backend/app');
const port = process.env.PORT || '3000';
app.set('port', port);
const server = https.createServer(app); //pass the express app to the server
server.listen(port);
and
//app.js
const express = require('express');
const app = express();
app.use((req, res, next) => {
console.log('This is the first middleware');
next();
});
app.get('https://api.scryfall.com/cards/named?fuzzy=aust+com', (req, res, next) => {
res.send('${res.body.name} is the name of the card!');
});
module.exports = app;
Any help would be greatly appreciated! Thanks in advance!
👨‍🏫 For an example, you can do it with this code below 👇:
const express = require('express');
const axios = require('axios');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use((req, res, next) => {
console.log('This is the first middleware');
next();
});
app.get('/', async (req, res, next) => {
try {
const result = await axios.get('https://api.scryfall.com/cards/named?fuzzy=aust+com');
res.status(200).send(result.data);
}catch(ex) {
console.log(ex.message);
}
});
app.listen(3000, () => {
console.log('Server is up');
})
💡 From the code above, you can call the endpoint: localhost:3000 and than you will get the result.
I hope it's can help you 🙏.
You can easily make a get request like this.
const express = require('express');
const app = express();
const port = 8080;
const bodyParser = require('body-parser');
//Expect a JSON body
app.use(bodyParser.json({
limit: '50mb' //Request size - 50MB
}));
app.get('/test', (req, res, next) => {
// do whatever you need here
res.status(200).send("ok");
});
app.listen(port, function () {
console.log(`Server is running.Point your browser to: http://localhost:${port}`)
});

Resources