Calling POST method by clicking a button - node.js

this is my first time when I'm setting up the server and need help. So my goal is to set up server by NodeJS and Expresss. Let's say we have an app with Admin and Users. When Admin clicks a button, it sends some data for the server, then Users can fetch the data.
So this is my server set up:
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port)
I can add some post method, let's say:
app.post('/', (req, res) => ....);
So I can prepare server reaction for listening the POST method, but I have no idea how to send some data from my app by clicking an button (I mean calling this post method). I've watched a bunch of tutorials and haven't seen any real-world exercises.

To receive the POST parameters, you need the body-parser module, which you can include in your app.js like this,
var bodyParser = require('body-parser');
app.use(bodyParser.json());
And here is how you can receive your form fields which are being sent through the POST method,
app.post('/', function(req, res) {
var someField1 = req.body.some_form_field;
var someField1 = req.body.form_field1;
});
Hope this helps!

On your express server
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.post("/", (req,res) => {
res.send("Hello");
});
On your webpage/app, You can use axios.
Lets say your express server running with localhost and port 4000.
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
var instance = axios.create({
baseURL: "http://localhost:4000" //use your express server's url(address) and port here
});
function onclick(){
instance.post("/").then( response => {
//response.data will have received data
}
}
</script>
You can use this function and call it on your button click

You can simply use jquery in your HTML page like this to call your api:
$("button").click(function(){
$.post("/", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
And Send data from your api:
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/', function(req, res) {
var obj = {};
obj.name="hello";
obj.lname="world"
res.json(obj);
});

Example:
HTML:
Your form elements should have name (it is mandatory) to access these in post body request.
<form method="post" action="/">
<input type="text" name="Name" />
<br>
<input type="text" name="Telephone" />
<br>
<input type="submit" />
</form>
app.js
const express = require('express')
const app = express()
const port = 3000
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.post('/', (req, res) => {
name = req.body.Name;
telephone = req.body.Telephone;
res.render('somefolder/index', {
name: name,
telephone: telephone,
});
// Above code is for reference if you want to load another page after post complete and get posted values in this page too.
res.end();
});

Related

What is the reason req.body is displayed as undefined?

Hi i am making a blog with node js. And now I am implementing the function to write a post, but there is a problem in this process.
new.ejs is a screen for creating a post.
new.ejs
<div>
<h2> new post </h2>
<form action="/articles" method = "POST">
<h4>title</h4>
<input required type="text" name = "title" / class='form-control'><br>
<h4>description</h4>
<textarea name="description" class = 'form-control'></textarea><br>
<h4>contents</h4>
<textarea id="mytextarea" name="contents" rows = '10'></textarea>
취소<button type = "submit" class="btn btn-primary">저장</button>
</form>
</div>
and
article.js
var express = require("express");
var app = express();
var router = express.Router();
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
router.get("/", function (req, res) {
res.send("article");
});
router.get("/new/home", function (req, res) {
res.render("articles/index");
});
router.get("/new", function (req, res) {
res.render("articles/new");
});
router.post("/", function (req, res) {
console.log(req.body.title);
});
module.exports = router;
Here, when req.body.title is executed, req.body becomes undefined. And in the code editor window, a sentence stating that bordyParser has been deprecated appears as the middle line is drawn. How to solve it
The EJS file is POSTing to /articles, but your POST route in the NodeJS is /.
To fix the 'body-parser is deprecated' messages, change the code as follows :-
...
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
...
to
...
app.use(express.urlencoded());
...
Body Parser is now part of Express itself.

Cannot read property of undefined / req.body returns undefined

I'm trying to do the most basic POST request in express but my req.body keeps returning undefined, I've googled similar issues but I can't find the solution that would work for me.
The form in HTML:
<form method="POST" class="vote">
<input type="text" name="test">
<button type="submit">TEST VOTE</button>
</form>
and in my post.js file
const express = require('express');
const app = express();
app.use(express.urlencoded({
extended: true
}));
app.post('/test', function (req, res) {
console.log('post to /test');
var data = req.body.test;
console.log(data);
What am I doing wrong here?
Try using body-parser node module which will parse the post data and append it on request object so that you can access it.
body-parser extract the entire body portion of an incoming request stream and exposes it on request.body.
const express = require('express');
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/test', function (req, res) {
console.log('post to /test');
var data = req.body;
console.log(data);
//rest of the code
}
Actually you didn't set the "action" field in your "form" tag.
You have to set your action field to
action= "/test"

How to receive image file to api server(Node.js)

I want to build api server by node.js.
and I want to post image file to my api server.
I was able to write GET method logic in my code
but, I have no idea write POST method logic.
plase help me
↓my code (node.js)
// preprocessing
// import library
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var fs = require('fs');
// post setting
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// port setting
var port = process.env.PORT || 3000;
// express setting
var router = express.Router();
router.use(function(req, res, next) {
console.log('Something is happening.');
next();
});
// main
// GET method
router.get('/', function(req, res) {
res.json({ message: 'Hello World' });
});
// POST method
router.route('/image')
.post(function(req1, res1) {
res1.json({image : req1.body});
});
// routing
app.use('/api/v1', router);
// start server
app.listen(port);
console.log('listen on port ' + port);
↓ tes curl command(GET)
curl -k -x GET "http://XXX/api/v1"
↓ curl result(GET)
"message" :"Hello World"
↓ test curl command(POST)
curl -k -X POST -F "images_file=#test01.jpg" "http://XXXX/api/v1/image"
↓ curl result(POST)
"image" :""
client side
<form action="/pictures/upload" method="POST" enctype="multipart/form-data">
Select an image to upload:
<input type="file" name="image">
<input type="submit" value="Upload Image">
</form>
server side use multer package and write post route as following
var express = require('express')
, router = express.Router()
, multer = require('multer')
var uploading = multer({
dest: __dirname + '../public/uploads/',
})
router.post('/upload', uploading, function(req, res) {
})
module.exports = router
for more detail take a look at this link image example

Invalid Token using expressjs csurf middleware example

I've tried using the expressjs csurf example from https://github.com/expressjs/csurf When using the first example in the Readme, (using Ejs template language), the token validation works fine. When I try using the 'Ignoring Routes' example, on the 'GET /form' to 'POST /process' execution(just as I did in the first example), I get 'invalid token' on the 'POST /process'. The token is being passed to the form on the GET. Any ideas?
Is 'app.use(csrfProtection)' not working? (used in the non working example, if I remove the 'use(csrfP..' and use the methodology from the working example to use the csrf module, IE, passing 'csrfProtection' to the 'get' and 'post' methods, the second example works)
Works:
var cookieParser = require('cookie-parser')
var csrf = require('csurf')
var bodyParser = require('body-parser')
var express = require('express')
// setup route middlewares
var csrfProtection = csrf({ cookie: true })
var parseForm = bodyParser.urlencoded({ extended: false })
// create express app
var app = express()
app.set('view engine', 'ejs')
// parse cookies
// we need this because "cookie" is true in csrfProtection
app.use(cookieParser())
app.get('/form', csrfProtection, function(req, res) {
// pass the csrfToken to the view
var tkn = req.csrfToken()
console.log(tkn)
res.render('index', { csrfToken: tkn })
})
app.post('/process', parseForm, csrfProtection, function(req, res) {
res.send('data is being processed')
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
html/ejs:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<form action="/process" method="POST">
<input type="hidden" name="_csrf" value="<%= csrfToken %>">
Favorite color: <input type="text" name="favoriteColor">
<button type="submit">Submit</button>
</form>
</body>
</html>
Does not work:
var cookieParser = require('cookie-parser')
var csrf = require('csurf')
var bodyParser = require('body-parser')
var express = require('express')
// setup route middlewares
var csrfProtection = csrf({ cookie: true })
var parseForm = bodyParser.urlencoded({ extended: false })
// create express app
var app = express()
app.set('view engine', 'ejs')
// parse cookies
// we need this because "cookie" is true in csrfProtection
app.use(cookieParser())
// create api router
var api = createApiRouter()
// mount api before csrf is appended to the app stack
app.use('/api', api)
// now add csrf, after the "/api" was mounted
app.use(csrfProtection)
app.get('/form', function(req, res) {
// pass the csrfToken to the view
var tkn = req.csrfToken()
console.log(tkn)
res.render('index', { csrfToken: tkn })
})
app.post('/process', parseForm, function(req, res) {
res.send('csrf was required to get here')
})
function createApiRouter() {
var router = new express.Router()
router.post('/getProfile', function(req, res) {
res.send('no csrf to get here')
})
return router
}
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app2 listening at http://%s:%s", host, port)
})
In your second example, you are not passing the csrfProtection middleware to the POST processing chain. It should be
app.post('/process', parseForm, csrfProtection, function(req, res) {
res.send('csrf was required to get here')
})

Usage of bodyParser.text() in Express with EJS

I am building a search engine app with Express that queries the Twitter API v1.1. Currently, I am trying to submit the search string to my server by parsing form data with the bodyParser module. Here is the code:
index.ejs
...
<form method="GET" action="/results">
<input id="input" type="text" name="search">
<button id="searchButton">+</button>
</form>
...
server.js
var express = require('express'),
bodyParser = require('body-parser');
var app = express();
var port = process.env.PORT || 8080;
app.set('view engine', 'ejs');
app.use(express.static(__dirname + "/public");
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.get('/', function(req, res) {
res.render('index');
});
app.get('/results', urlencodedParser, function (req, res) {
console.log(req.body);
res.render('results')
});
app.listen(port, function() {
console.log('Our app is running on http://localhost:' + port);
});
The code shown will return { } to the console. If I try and access req.body.search it returns undefined (obviously). What is the issue here? Why is it not logging my search string?
You're using the wrong body decoder. If you're submitting a form (application/x-www-form-urlencoded is the default enctype for forms), you will need bodyParser.urlencoded() instead of bodyParser.text(). The latter is for plaintext request data, not form data.
Additionally, you should also be using method="POST" and a POST route (app.post('/results', ...)) instead of method="GET" and a GET route. Since GET requests almost never have a body, the browser instead transforms the form data into a querystring that is then appended to the url itself. This means your form data is currently in req.query instead of req.body. Switching to POST though will cause the browser to send the form data in the request body, and the form data will be in req.body as expected.

Resources