How to handle parameter in POST request in expressJS - javascript

I am working on my first project in my company and stuck at post request using expressjs.
Below is my code for post request
const express = require('express')
const app = express()
const request = require('request')
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: true}))
app.use(bodyParser.json())
app.post('/cruamsApi/updateUsers', (req, res) => {
const DisplayName = req.body.DisplayName
const EmployeeNumber = req.body.EmployeeNumber
const RegDate = req.body.RegDate
const url = 'http://localhost:8009/CruAmsAPI/Employee'
request (
{
url: url,
json: true,
body: {
"EmployeeNumber": EmployeeNumber,
"DisplayName": DisplayName,
"RegDate": RegDate
}
},
function (error, response, body) {
if(!error) {
res.send(response)
} else {
res.send(error)
}
}
)
})
app.listen(PORT, () => {
console.log('server is listening port ' + PORT)
})
When I make a POST request, it is keep returning "EmployeeNumber parameter is required" error message from an API. I tried to double quote the keys "EmployeeNumber" but still having a same issue. Included headers too but didn't really work. POST request does work in POSTMAN.

Have you tried to send the EmployeeNumber in your request?
If it works in Postman, it should work. I think that your issue is in your front-end which doesn't send any EmplyeeNumber in the request.

Related

How to get file data and other form data sent in POST request in Node Js

I am sending form data values using Postman as given here. Postman Request.
I am making use of NodeJS server in the backend to get the data from this POST request.
The code for my app.js file is given below.
require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const port = process.env.PORT || 8080;
const app = express();
app.use(bodyParser.json({
limit: '50mb',
}));
app.use(bodyParser.urlencoded({
limit: '50mb',
extended: true
}));
const { multerUploadOneFile } = require(path.resolve(__dirname, 'helpers', 'multerConfig'));
app.post('/upload', function (req, res) {
// **Here I need to get the other parameters in the request body, i.e ```userId```, ```fileType```
console.log(req.body);
multerUploadOneFile(req, res, function (error) {
if (error) {
return res.status(401).send({
status: 'failure',
message: error.message
});
}
return res.status(200).send({
status: 'success',
message: 'successfully uploaded file.',
});
})
});
I am logging the request body in /upload api endpoint but I am not able to get anything. Please let me know how can I get the req.body in callback of /upload api endpoint.
body-parser doesn't support multi-part bodies.
multer (which you're correctly using) does, however it needs to execute and parse the request before you'll be able to access anything.
multerUploadOneFile needs to execute before you have acceess to .body or .file.
app.post('/upload', function (req, res) {
multerUploadOneFile(req, res, function (error) {
console.log(req.body, req.file);

Put request req.body is empty

As all my requests are working fine, I have a problem with the put. req.body stays empty and then gives that error :
errmsg: "'$set' is empty. You must specify a field like so: {$set:
{: ...}}"
PUT :
router.put('/books/:name', (req, res, next) => {
const localdb = db.client.db(process.env.DB_NAME);
const collection = localdb.collection(process.env.COLL_BOOKS);
collection.replaceOne(
{ "name": req.params.name },
{ $set: req.body },
function (err) {
if (err) throw err
res.status(201).send(true);
});
App.js
const express = require('express'),
app = express();
os = require('os');
const bodyParser = require('body-parser');
const cors = require('cors');
const router = require('./router.js')
require('dotenv').config()
app.use(cors());
app.use(bodyParser.json());
app.use('/api/v1', router);
const port = (process.env.PORT || '3001');
let server = app.listen(port, os.hostname(), () => {
let host = server.address().address,
port = server.address().port;
console.log("Example app listening at http://%s:%s", host, port);
});
axios request :
updateItem = newBook => {
Axios.put(process.env.REACT_APP_API_PATH_BOOKS + `${newBook.name}`, newBook)
.then(res => {
this.setState({ newBook: res.data });
this.props.history.push('/admin');
})
.catch(err => console.log(err));
}
I don't understand what I am doing wrong
Make sure you don't have any middlware stripping or incorrectly parsing the body. For instance, you may have a JSON body parser, and not be sending JSON data with JSON application headers.
Can you give a bit of context, in code, for how you are making the put request and also the result of logging the req in a pastebin?

Node.js REST endpoint not catching parameters passed from axios request

I'm making a POST request from a React front-end using axios to an endpoint to save some data to my DB (MongoDB). I'm getting an error that one cannot read property 'name' of undefined. I think that's occurring because req.body is undefined but I can't understand what's wrong with my axios request. I logged all the parameters and they are there (not undefined). The axios request and the endpoint are written below. Any help will be appreciated. Thanks!
Axios Request
const uploadElement = async (name, HTMLCode, JSCode, CSSCode, screenshot) => {
console.log(name)
try {
await axios({
method: 'post',
url: '/api/elements',
data: {
name: name,
HTMLCode,
JSCode,
CSSCode,
screenshot
}
});
} catch (e) {
console.log(e);
}
}
Endpoint for POST Request
router.post("/", upload.single("screenshot"), async (req, res) => {
try {
const newElement = new Element({
name: req.body.name,
JSCode: req.body.JSCode,
HTMLCode: req.body.HTMLCode,
CSSCode: req.body.CSSCode,
screenshot: req.file.buffer,
});
await newElement.save();
res.send("Data uploaded successfully!");
} catch (e) {
console.error(e);
}
});
Server.js
const express = require("express");
const passport = require("passport");
const session = require("express-session");
const cors = require('cors');
const elementRouter = require("./routes/elementRoute");
const authRouter = require("./routes/authRoute");
const connectDB = require("./config/db");
const app = express();
const port = process.env.PORT || 5000;
connectDB();
app.use(
session({
secret: "googleOAuth",
resave: false,
saveUninitialized: true,
})
);
app.use(cors());
// Passport Config
require("./config/passport")(passport);
app.use(passport.initialize());
app.use(passport.session());
app.use("/api/elements", elementRouter);
app.use("/api/auth", authRouter);
app.listen(port, () => {
console.log(`Server is up on port ${port}`);
});
You need to install and require body-parser in your serverside code
First run npm i --save body-parser
Then require it like this
const bodyParser = require("body-parser");
Then use it after you declare your app ( after this line const app = express();)
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
This makes the data of your request available in req.body

Cannot POST to Express router (404 error)

I cannot fetch POST requests to my Express router. I have many GET requests which work fine, but this is my first POST request and it is not working.
My frontend code looks like this:
export async function postHamster(name, age) {
try {
await fetch('/hamsters/api/new-hamster',
{
method: 'POST',
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name: name,
age: age
})
})
console.log("postHamster has run") //LOGGED
}
catch (e) {
console.error(e)
}
}
The response will always be:
fetchData.js:38 POST http://localhost:3000/hamsters/api/new-hamster 404 (Not Found)
I have triple-checked the path and it cannot be in error. The backend path is "router.get('api/new-hamster', async (req, res)..." in the file 'hamsters.js'.
I have also put the backend function at the very top of its file, to ensure that it is not overrruled by any other function in the file.
This is my server.js:
// THIS FIRST FUNCTION I JUST COPIED FROM A SOLUTION BUT IT DOES NOT SEEM TO HELP
// routes/index.js
module.exports = (express) => {
// Create express Router
var router = express.Router();
// add routes
server.route('/hamsters/api/new-hamster')
.post((req, res) => {
res.setHeader('Content-Type', 'application/json');
res.send('You sent: sdadad to Express');
});
return router;
}
const express = require('express');
const server = express();
const serverPort = process.env.PORT || 1234;
server.use(express.static(__dirname + '/../build'))
let data = require('./data.json')
const { Router } = require('express');
let router = new Router();
//USE BODY-PARSER BEFORE REGISTERING ROUTES!
const bodyParser = require('body-parser')
server.use(bodyParser.urlencoded({ extended: true }));
server.use(bodyParser.json())
server.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
// ROUTES
const hamstersRoute = require('./routes/hamsters');
const chartsRoute = require('./routes/charts')
const gamesRoute = require('./routes/games')
const statsRoute = require('./routes/stats')
const imagesRoute = require('./routes/images')
const uploadRoute = require('./routes/upload')
server.use('/assets', express.static("assets"))
server.use(express.static('public'))
server.use('/hamsters', hamstersRoute)
server.use('/charts', chartsRoute)
server.use('/games', gamesRoute)
server.use('/stats', statsRoute)
server.use('/images', imagesRoute)
server.use('/upload', uploadRoute)
server.listen(serverPort, () => {
console.log(`Server is up n running on port ${serverPort}!`)
})
module.exports = data;
I have looked at these threads:
Cannot GET/POST with express Router()
Express.js routers post request returns 404
Express: router cannot read POST request
Have you checked the url you're trying to post to in the network tab in the console? I think you need to add a / before api in the backend route: router.get('/api/new-hamster', async (req, res)...".
You have this:
server.use(bodyParser.urlencoded({ extended: true }));
Instead of this:
server.use(bodyParser.urlencoded({ extended: false }));

Node JS POST request returning undefined body

Quite new to Node JS and I am trying to post to a specific URL and retrieve the data.
I am using postman to do this but every time I post to it the response data is undefined but the status code is 200.
I have added body-parse as suggested but still no joy.
I will post my server code and request below.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = process.env.PORT || 5000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/api/hello', (req, res) => {
res.send({ express: 'Hello From Express' });
});
app.post('/api/save-json', (req, res) => {
console.log(req);
res.send(
`I received your POST request. This is what you sent me: ${req.body.json}`,
);
});
app.listen(port, () => console.log(`Listening on port ${port}`));
My postman request is:
{
"body" :
{
"json": "some data"
}
}
Any ideas?
body is the property in the req object containing the HTTP request body (which is set by body-parser), since you're sending in an object called body you'll need to access it like this: req.body.body.json

Categories