nodejs express req.body undefined - node.js

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

Related

TypeError: handlebars is not a function error

I am a newbie of node.js, i use template engine express-handlebar but i get problem is: **TypeError: handlebars is not a function at Object. ** . I have search lot but not any answer to fix. my code is below:
const morgan = require('morgan');
const handlebars = require('express-handlebars');
const app=express();
const port =3000;
// hTTP logger
app.use(morgan('combined'));
//templace engie
app.engine('handlebars',handlebars());
app.set('view engine','handlebars');
app.get('/',(req,res)=> {
return res.send('hello world');
});
app.listen(port,()=>console.log(`Example app listening at http://localhost:${port}`));````
For version 6.0.2, the express-handlebars package exports create, engine function. See source code The basic usage should be:
const { engine } = require("express-handlebars");
const express = require("express");
const app = express();
const port = 3000;
//templace engie
app.engine("handlebars", engine());
app.set("view engine", "handlebars");
app.get("/", (req, res) => {
return res.send("hello world");
});
app.listen(port, () =>
console.log(`Example app listening at http://localhost:${port}`)
);

How to read a file in node js?

When i want to read a file in node js it won't display the file in the browser when I execute.
and in the terminal says no such file or directory while I use the exact file path anyone can answer this why?
Here is the code:
const express = require('express');
const app = express();
const fs = require('fs');
const bodyParser = require('body-parser');
const CORS = require('cors');
let port = 3000;
app.use(CORS());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));
app.use(express.static('Docs'));
app.get('/', (req, res) => {
res.json({name: 'waris', favFood: 'Pizza'})
fs.readFile('./docs/index.html', (err, data) => {
if(err){
console.log(err)
}else{
res.send(data);
}
})
})
app.listen(port, () => {
console.log(`Running on port ${port}`);
})

my app have a problem after i refresh the page

when i open my app for the first time it work just fine but when i refresh the page it give me a url to my index.html file ( /client/build/index.html ) , i have deploy it on heroku
that is the code in my app.js file that create the server
const express = require('express');
const app = express();
const path = require('path');
// create a server for socket io
const http = require('http');
const socketio = require('socket.io');
const server = http.createServer(app);
module.exports = io = socketio(server);
// my middle ware
const morgan = require('morgan');
const bodyParser = require('body-parser');
// Init Middelware
app.use(express.json({ extended: false }));
// my router
const postRoute = require('./nodeapi/routers/post');
const authRouter = require('./nodeapi/routers/auth');
const usersRouter = require('./nodeapi/routers/users');
const friendRouter = require('./nodeapi/routers/friend');
const chatRouter = require('./nodeapi/routers/chats');
const mongoDB = require('./nodeapi/mongodb-database/db');
const port = process.env.PORT;
// Connect monogo database
mongoDB();
// Middel ware
app.use(morgan('dev'));
app.use(bodyParser.json());
// Get the routes
app.use('/', postRoute);
app.use('/', authRouter);
app.use('/', usersRouter);
app.use('/', friendRouter);
app.use('/', chatRouter);
app.use('/file/', express.static('./uploads/'));
// connect to socket io
io.on('connection', (socket) => {});
//Serve static assets in productio
if (process.env.NODE_ENV === 'production') {
// Set static folder
app.use(express.static('./client/build'));
app.get('*', (req, res) => {
res.send(path.resolve(__dirname, '..', 'client', 'build', 'index.html'));
});
}
// listen to the port
server.listen(port, () => {
console.log(`this is port ${port}`);
});
this is when i open it for the first time
this is when i refresh the page
You just need to send it as file not a text
app.use(express.static('./client/build'));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, '..', 'client', 'build', 'index.html'));
});

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