I have been trying to pass data from my React component to the node server.js.
In my React component, inside the componentWillMount, I am making an axios post call and pass countValue.
Here is my code for the React Component:
componentWillMount = () => {
axios.post("/", {
countValue: 12
});
}
Inside my server.js, I am simply trying to get countValue through req.body.countValue. However, it is always set to "undefined".
req.body just comes out to be empty object, {}.
Here is my code for the server.js
const express = require('express');
const bodyParser = require('body-parser');
const engines = require('consolidate');
const app = express();
app.engine("ejs", engines.ejs);
app.set('views', __dirname);
app.set("view engine", "ejs");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/", (req, res) => {
console.log(req.body.countValue);
res.render("index");
});
Could anyone please help me with this issue?
you are making POST request with axios from the frontend,
and configured in the server to listen to GET only...
in the express add:
app.post("/", (req, res) => {
console.log(req.body.countValue);
res.render("index");
});
very strange... i tested it and it working,
if you making small app without the react ... it's working?
this is the full test that worked for me:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', (req, res) => {
res.render('so');
});
app.post('/', (req, res) => {
console.log("countValue =", req.body.countValue);
res.render('so');
});
app.listen(3000, () => {
console.log('app now listening on port 3000');
});
and the HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>SO</title>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script type="text/javascript">
axios.post("/", {
countValue: 12
});
</script>
</head>
<body>
</body>
</html>
Related
I know this has been asked multiple times, but I have been looking around and still can't find an answer to my problem.
const express = require("express");
require("dotenv").config({
path: ".env",
});
const PORT = process.env.PORT || 5000;
const runDatabase = require("./config/database");
const path = require('path')
const app = express()
const cors = require('cors')
app.use(cors())
app.use(express.json())
app.use("/uploads", express.static(path.join(__dirname, "uploads")));
// routers
const userRouter = require("./router/usersRouter");
const categoryRouter = require("./router/categoryRouter");
const productRouter = require("./router/productRouter");
app.use("/api", userRouter);
app.use("/api", categoryRouter);
app.use("/api", productRouter);
app.listen(PORT, () => {
runDatabase();
console.log(`πThe Backend Server is up and running on port ${PORT}π`);
});
Here is my code, when sending the request in JSON raw postman a response is what I need but when using a form-data it will return an empty body
app.use(express.urlencoded({ extended: false }));
Try to add this to your middlewares. After express.json()
Change app.use('/', (req, res) => { to app.get('/', (req, res) => {.
app.use is intended for middleware, not normal requests.
Read more about app.use and it's usages here: http://expressjs.com/en/4x/api.html#app.use
JS,
I have an express app with some routes. When my router doesn't match any route it will display index.html instead of going to route '/*' and redirect to a specific route.
I don't understand why my router doesn't go to app.get('/*') because when I type https://my-domain.com I want to be redirect to https://my-domain.com/test?id=1.
Maybe I can do something with express-static but I don't know how.
And if I name my file home.html instead of index.html it's work perfectly.
Here is a small piece of my code :
const express = require('express');
const path = require('path');
const cors = require('cors');
const app = express();
const bodyParser = require("body-parser");
const ejs = require('ejs');
const csrf = require('csurf');
const port = 3080;
let csrfProtection = csrf({ cookie: true })
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(csrfProtection);
app.engine('html', ejs.renderFile);
app.set('view engine', 'html');
app.use(function (err, req, res, next) {
if (err.code !== 'EBADCSRFTOKEN') return next(err)
res.status(403).json({error: "Invalid CSRF Token"});
})
app.post('/roles', csrfProtection, (req, res) => {
/*...*/
});
app.get('/test', csrfProtection, (req, res) => {
/*...*/
});
app.all('/*', csrfProtection, (req,res) => {
if(Object.keys(req.query).length == 0) {
res.redirect("https://my-domain.com/test?id=1");
}
res.render(path.join(__dirname + '/index.html'), {csrfToken: req.csrfToken()});
});
app.listen(port, () => {
console.log(`Server listening on the port::${port}`);
});
My files structure is :
home
static
css
js
index.html
index.js
At the request for https://my-domain.com, write res.redirect('/foo/bar'), where /foo/bar is the url you want to redirect to.
See Official Documentation For res.redirect(): http://expressjs.com/en/api.html#res.redirect
So I'm developing a chat server using expressjs and socketio and decided to create an admin where backend built in with the node chat server itself.
const express = require("express");
const app = express();
const port = 3700;
let io = require('socket.io').listen(app.listen(port));
let socketList = io.sockets.server.eio.clients;
const path = require('path');
const bodyParser = require('body-parser');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));
app.get('/login', function(req, res) {
res.render('login', { title: 'Login | Argos Chat' });
});
app.post('/login', function(req, res) {
console.log(req.body);
});
So upon login data submission, I tried to display the post data from the login form but it returns me an empty object {}
console.log(req.body);
Tried to do req.params but same result .Any help, ideas is greatly appreciated.
I tried running your code and its working fine. Maybe the way you are calling the API is not right
To support content-type: x-www-form-urlencoded you should use
app.use(bodyParser.urlencoded({ extended: true }));
and to support content-type: application/json you should use
app.use(bodyParser.json());
I think you are using form-data, for that neither of these will work. For that you may want to use formidable package. We should use form-data content type only when we are sending any images/file.
And body-parser has been merged with express. You can directly use this now
app.use(
express.json(),
express.urlencoded({ extended: false })
);
I think this might be a right solution for your problem, as everything seems to be right in your code, the error might be caused by the way you are calling the API and you are setting the headers:
https://stackoverflow.com/a/25904070/12090205
const express = require("express");
const app = express();
const port = 3700;
let io = require('socket.io').listen(app.listen(port));
let socketList = io.sockets.server.eio.clients;
const path = require('path');
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));
app.get('/login', function(req, res) {
res.render('login', { title: 'Login | Argos Chat' });
});
app.post('/login', function(req, res) {
console.log(req.body);
});
I checked Its Working.
express js the body undefined error
I shared the files below. I got very angry. No error appears. Please help me.
Although I do it again I get the same error
I searched a lot but none of the solutions worked.
main.js
const express = require('express')
const router = express.Router()
router.get('/', (req,res)=>{
res.render('site/index')
})
router.get('/login', (req,res)=>{
res.render('site/login')
})
router.get('/register', (req,res)=>{
res.render('site/register')
})
router.get('/postcreate', (req,res)=>{
res.render('site/postcreatepage')
})
router.get('/postupdate', (req,res)=>{
res.render('site/postupdatepage')
})
router.post('/post/post', (req,res)=>{
console.log(req.body)
})
module.exports = router
I checked and searched many times could not solve
app.js
const express = require('express')
const path = require('path')
const app = express()
const port= 3000
const hostname = '127.0.0.1'
const mongoose = require('mongoose')
const main = require('./routes/main')
var bodyParser = require('body-parser');
app.use('/', main)
app.use(express.static('static'))
mongoose.connect('mongodb://127.0.0.1/nodemon_db',{
useNewUrlParser: true,
useUnifiedTopology:true
})
app.engine('handlebars', require('exphbs'))
app.set('view engine','handlebars')
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.listen(port, hostname, ()=> console.log(`Example app listening on port http://${hostname}:${port}/`))
Although I do it again I get the same error
html
<html>
<head>
</head>
<body>
<form action="post/post" method="post">
<input name="title"><br>
<input name="content"><br>
<button type="submit">But</button>
</form>
</body>
</html>
In your route, you have to return a response other wise the request will hang:
main.js
router.post('/post/post', (req,res)=>{
console.log(req.body)
const resObject = {
... do something with req.body ...
};
return res.status(201).json(resObject);
});
In your app entrypoint, set your routes after your config and middleware:
app.js
const express = require('express')
const path = require('path')
const app = express()
const port= 3000
const hostname = '127.0.0.1'
const mongoose = require('mongoose')
const main = require('./routes/main')
var bodyParser = require('body-parser');
/* config */
mongoose.connect('mongodb://127.0.0.1/nodemon_db',{
useNewUrlParser: true,
useUnifiedTopology:true
})
/* Middleware */
app.use(express.static('static'))
app.engine('handlebars', require('exphbs'))
app.set('view engine','handlebars')
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
/* Routes */
app.use('/', main)
app.listen(port, hostname, () => console.log(`Example app listening on port http://${hostname}:${port}/`)
i wrote a code sample for express js and it is working but when I use app.post or app.get instead of app.use the code does not work and the ide (webstorm) does not recognize the app.post or app.get too
is it replaced with something in the newer versions of express or something?
here is my code:
const express = require('express');
let app = express();
app.use('/addp',(req,res,next)=>{
res.send("<form action='/product' method='post'><input type='text' name='entry'><button type='submit'>add</button></form>")
})
app.use(express.urlencoded({extended:true}));
//next line does not work
//if I use app.use it will work fine
app.get("/product",(req,res)=>{
console.log(req.body);
res.redirect('/');
})
app.use('/',(req,res)=>{
res.send("<h1>done</h1>")
})
app.listen(3000);
Your code is working fine. For the print body, you should have to use bodyParser in express js.
const express = require('express');
let app = express();
var bodyParser = require('body-parser')
app.use('/addp', (req, res, next) => {
res.send("<form action='/product' method='post'><input type='text' name='entry'><button type='submit'>add</button></form>")
})
app.use(express.urlencoded({ extended: true }));
app.use(
bodyParser.json({
limit: "250mb"
})
);
app.use(
bodyParser.urlencoded({
limit: "250mb",
extended: true,
parameterLimit: 250000
})
);
app.get("/product", (req, res) => {
res.send("Get Request")
})
app.post("/product", (req, res) => {
console.log("-------------")
console.log(req.body);
console.log("-------------")
res.send("Post Request")
})
app.use('/', (req, res) => {
res.send("<h1>done</h1>")
})
app.listen(3000);
It is this:
app.route('/product/').get(function (req, res) {
If u want to add multiple routes let's say api, u will do this:
In some module api.js:
const apiRoutes = express.Router();
apiRoutes.get('/some', () => {});
apiRoutes.post('/some', () => {});
Then let's say your server:
app.use('/api', apiRoutes);