Error 'Pride not defined' when using app.post in Express - javascript

Following this course on NodeJS here:
https://app.pluralsight.com/player?course=api-design-nodejs-express-mongo&author=scott-moss&name=91bae158-711d-4af0-a44d-7f48435436b9&clip=3&mode=live
https://github.com/leongaban/api-design-node/blob/step-2-fix/server/server.js
I have the following simple server:
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
const path = require('path')
const port = 3000
app.use(express.static('client'))
app.use(bodyParser.urlencoded({ extended: true }))
const lions = []
let id = 0
app.get('/lions', function(req, res) {
res.json(lions)
})
app.get('/lions:id', function(req, res) {
let paramId = req.param.id
let lion = lions.filter((lion.id === paramId))
res.json(lion || {})
})
app.post('/lions', function(req, res) {
let lion = req.body
id++
lion.id = id + ''
console.log('lion', lion)
lions.push(lion)
res.json(lion)
});
app.listen(port, () => console.log(`NODE RUNNING on port: ${port}`))
In the frontend client code I am able to send the following request data:
age: "3"
gender: "female"
name: "1"
pride: "2"
However in the server my log console.log('lion', lion) returns just this: lion { id: '1' } the req.body is empty.
Then in the frontend console I get this error:
VM1567:3 Uncaught (in promise) ReferenceError: pride is not defined
Thoughts on where pride is expected? And why the req.body is empty on the server?

I forgot to use this middleware:
app.use(bodyParser.json())

Related

Express.JS Body Parser Returns Undefined

I've been trying to parse a body request and I always get undefined. I've included both app.use(express.json()); and app.use(express.urlencoded({ extended: false })); in my code but it still returns undefined. This is my code:
const express = require("express");
const path = require("path");
const fs = require("fs");
const jokes = require("./jokes.json");
app.post("/api/jokes", (req, res) => {
const newJoke = {
question: req.body.question,
answer: req.body.answer
};
console.log(req.body.question); // Logs Undefined
});
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`Server is running and listening on port ${port}...`);
});
Any idea?

TypeError: Cannot read property 'message' of undefined<br>

I am getting an error of TypeError: Cannot read property 'message' of undefined<br> on a Postman post request for a express server code.
Server.js
const express = require('express');
const {v4: uuidv4} = require('uuid');
const app = express();
// Middleware for data on post request
app.use(express.json({extended: false}));
// Data
const todos = [
{
message: "Buy tea",
id: 1
},
{
message: "Buy wrp for lunch",
id: 2
},
{
message: "Play game",
id: 3
}
];
/* --------- API ---------- */
app.get("/", (req, res) => {
res.status(200).json(todos);
})
app.post("/", (req, res) => {
const newtodo = {
message: res.body.message,
id: uuidv4()
}
todos.push(newtodo);
res.status(201).json(todos);
})
const PORT = process.env.PORT || 5001;
app.listen(PORT, () => {
console.log(`Server running on port: ${PORT}`);
} );
On Headers I have Key Content-type Value application/json. But I keep getting the error. The screenshot is down below:
Can't seem to pinpoint the issue. Message is defined on my server.js file.
I think here should be req.body.message instead res.body.message
app.post("/", (req, res) => {
const newtodo = {
message: req.body.message,
id: uuidv4()
}
todos.push(newtodo);
res.status(201).json(todos);
})
If I'm wrong you can use optional chaining like this res?.body?.message.
Javascript Optional Chaining

node.js post method req.body undefined even with body-parser

Hello guys I am working with node js to use dialogflow chat bot ,
I am trying to get parameters from http request post methode
I used postman for that and yes I did set up the content type to json in the header , I have the following code for my request body :
{
"text":"hello"
}
and the following link
http://localhost:5000/api/df_text_query
I have the following index.js file :
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
require('./routes/dialogFlowRoutes')(app);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }))
app.get('/',(req , res)=>{
res.send({'hello':'Johnny'});
});
const PORT = process.env.port || 5000;
app.listen(PORT);
this my dialogflowRoutes.js file :
const dialogflow = require('dialogflow');
const config = require('../config/keys');
const sessionClient = new dialogflow.SessionsClient();
const sessionPath = sessionClient.sessionPath(config.googleProjectID, config.dialogFlowSessionID);
module.exports = app => {
app.get('/', (req, res) => {
res.send({ 'hello': 'world!' })
});
app.post('/api/df_text_query', async (req, res) => {
console.log(req.body)
const request = {
session: sessionPath,
queryInput: {
text: {
text: req.body.text,
languageCode: config.dialogFlowSessionLanguageCode
}
}
};
let responses = await sessionClient
.detectIntent(request);
res.send(responses[0].queryResult)
});
app.post('/api/df_event_query', (req, res) => {
res.send({ 'do': 'event query' })
});
}
this is the error I get when I send the following request
dialogFlowRoutes.js:17
text: req.body.text,
^
TypeError: Cannot read property 'text' of undefined
Order in which you initialize middleware matters.
You must parse body before you act on it. Move your routing middleware after you initialize bodyParser, like below:
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }))
require('./routes/dialogFlowRoutes')(app);

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?

Getting error 405 when sending request on express route in next js

I create routes on Express js in Next js. When i deployed on hosting and sent request on route i getting error 405, but when i do same on localhost everything all right.
I cant understand that is this?
const express = require('express')
const next = require('next')
const bodyParser = require('body-parser')
const PORT = process.env.PORT || 3000
const dev = process.env.NODE_ENV !== 'production' //true false
const nextApp = next({ dev })
const handle = nextApp.getRequestHandler() //part of next config
nextApp.prepare().then(() => {
const app = express()
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const apiRoutes = require("./routes");
app.use('/api', apiRoutes)
app.get('*', (req,res) => {
console.log('asdfasdfasdfd')
return handle(req,res)
})
app.listen(PORT, err => {
if (err) throw err;
console.log(`ready at http://localhost:${PORT}`)
})
})
I think your express config has problem.
your express server must be like this:
const express = require('express')
const next = require('next')
const handler = routes.getRequestHandler(app)
const app = next({ dir: '.', dev })
app.prepare().then(() => {
const server = express()
server.post('/api', (req, res) => {
handler(req, res, req.url)
)
server.get('*', (req, res) => {
handler(req, res, req.url)
})
}
check the code for server.get and server.post or other http methods.
Error 405 tells that the method is not allowed.
Vercel can't use custom server with next js
https://github.com/vercel/next.js/discussions/13306

Categories