How to "catch" a form's post request status? - node.js

I am using Node.js(with express) to make a website and I'm pretty new at it. I am currently stuck on how to "catch"(not sure the proper term) a POST request response on the client side. I have a page that has a form that the user fills out. Once the user hit the submit button the server-side gets the information and process it. Then once done it sends a status code. What I want to do on the client side is "catch" that status code, depending on the code, if its good then redirect to the next page else pop up an alert to the user that something is wrong with their input(or something along those lines). If someone can show me the most simplest way of doing it, as I am still learning, I would appreciate it.
When I hit submit it changes my browser window blank with a text: 'OK'
index.html
<!DOCTYPE html>
<html>
<head><title>Index</title></head>
<body>
<form action="/create" method="POST">
<input type="text" name="input1" value="Message"></br>
<input type="number" name="input2" value="0"></br>
<input type="submit" value="Submit">
</form>
<script src="app.js"></script>
</body>
</html>
app.js
//where I want to "catch" my post request response
index.js
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
app.use(express.static(__dirname+'/views'))
app.use(bodyParser.urlencoded({extended:true}))
app.use(bodyParser.json())
app.post('/create', function(req, res){
//abstract data and send to db
if(okay)
res.sendStatus(200)
else
res.sendStatus(400)
})

When I hit submit it changes my browser window blank with a text: 'OK'...why can't I use a HTML form submission?
That's because if it is a plain HTML form submission, the browser will send the HTTP request, get response from server, and display that response content as a new web page (and replace the old one).
Why I have to use an Ajax request?
To get resonse from server without refresh the page, you need to send an Ajax request. That is, send the HTTP request via JavaScript, rather than via HTML element. In this way, the response can be processed by JavaScript code ("if its good then redirect to the next page else pop up an alert").
Example Ajax code is listed as below (using jQuery):
$.post('/create', {
input1: 'Message',
input2: 0
}).done(function(){
// redirect to the next page.
}).fail(function(){
// pop up an alert
});

Related

How to get dynamic parameter from html form in ajax

I have system for liking/unliking posts and I don't want page refresh to occur when user likes post. I want to use ajax to prevent that but don't know how to fetch
<form action="/posts/like/{{post.id}}" method="POST" id="like-form">
<button type="submit" id="like-button">Like</button>
</form>
How to fetch this {{post.id}} in ajax, I've tried using form.action but that returns whole url i just want id of certain post
You're not clear what are you using for the back-end like API built with Node or you're using templating engine with Node, but you can try this on front-end to achieve it.
document.querySelector('#like-form').addEventListener('submit', function(e) {
e.preventDefault(); // this prevents page refresh
fetch(`/posts/like/${post.id}`, { method: 'POST' });
});

Render view as result of POST request in Express

I have a basic node app which is integrated with stripe. The client-side javascript generates a token which is sent in a POST request to the server. The server then sends the stripe API the token which makes the payment. I want to redirect the user to a page showing some info e.g. Payment successful or Error making payment.
When I put res.render("/charge", {<some-JSON>}); in the code that handles the POST request, it sends the page /charge as a response to the POST request. Is there a way to send the user a page as a response instead of sending the POST request the response?
Node Snippet:
app.post(req, res) {
// Some Code
}
From what I gather from your post and comments. You are looking for a way to display Stripe response data into your webpage.
Instead of doing your traditional AJAX request with client-side JavaScript, use a form to submit the data to your server-side.
<form action="/stripe" method="post">
<input type="text" value="whatever" name="batman">
<button type="submit">Pay</button>
</form>
On your server-side, create an endpoint, using app.use('/stripe'), as an example, but the endpoint has to match your value in the action="" attribute. Then simply render the page with the stripe response.
app.use('/stripe', function(req, res) {
// whatever code
res.render('/charge', {JS OBJECT});
});

Running a node.js file from a click event

I am new to node.js. I am connecting with an api with express/node.js with ejs templating. I wanted to push some information from the browser to the api. At the moment, I can push from the command line. I understand I cannot call a node.js file from the browser directly but I was wondering when I click submit on a form if it can call node.js file and run it...what should I use, modules, routes, ajax, or any other solutions you recommend? I appreciate the help.
Well, it's a strange question. Your Node application needs to either listen for HTTP requests or WebSocket connections (possibly using some abstraction like Socket.io that can provide fallbacks where WebSocket is not available) and handle the requests or messages sent on the socket. In those handlers you can do whatever you need. This is just a basic principle of client/server architecture.
Now, to choose what technology is best suited for your needs it all depends on how often you need to make that communication, whether or not you need realtime communication, how much data do you need to pass around, if you need to support serving data initiated by the server or only by the client etc.
To answer you question - yes, you can submit a form and make it execute some code in your Node application. This is exactly how forms work - they make a connection, usually GET with data in the query string or POST with data in the body (both can easily be read by Node) and then your handler on the backend handles the request, does whatever it needs and sends a response.
Consider this simple example using express and body-parser:
const app = require('express')();
const { urlencoded } = require('body-parser');
app.use(urlencoded({ extended: true }));
app.use('/', (req, res) => {
const { method, path } = req;
const { x } = req.body;
console.log(`Client request: ${method} ${path} (x = ${x})`);
res.end(`
<!doctype html>
<html>
<head>
<title>Form handling example</title>
</head>
<body>
<p>x = ${x}</p>
<form method="POST" action="/">
Enter x: <input type="text" name="x">
<input type="submit" value="Submit">
</form>
</body>
</html>
`);
});
app.listen(4447, () => console.log('Listening on http://localhost:4447/'));
Create a new directory, save this code as server.js, run:
npm init -y
npm install express body-parser -S
node server.js
and access the printed URL in the browser.
When you click the submit button you'll see what will happen in the Node app.
Your node app will have a route set up which accepts GET or POST requests. Then it does some logic and returns some data in a response.
Your web page will send the form to your node route as GET or POST via an AJAX call, and likewise it will receive a response from the AJAX call. Then you can take this response and use it locally in the webpage however you like.

Don't redirect on POST express.js

I'm making a basic web app with Node.js and Express 4 and I'm trying to implement a "follow" function. I did some inspecting on the Github website and noticed it used a form with a follow button that would post to the server to follow a user. I think this sounds like a good approach but when I post I don't want to have to reload the page just like the github website.
How does one this inside of Express 4? Everything I put inside the .post route always end up in a page load. I'm pretty sure in jQuery's ajax method you can just return false and nothing will happen to the page, just the request will be sent which is what I want to happen because I'm using a RESTful api and I want to add the user to the current user's following but I don't want to have to use jQuery just for this function. I would prefer it be done in Express if possible, though any help would be appreciated.
views/user.handlebars
<h1>{{user.displayName}}</h1>
<p>#{{user.username}}</p>
<form action="" data-userid="{{user._id}}" method="post">
<button name="follow" type="submit">Follow</button>
</form>
routes/users.js
app.route('/:username')
.get(function(req, res) {
// get :username user from api and load info
...
})
.post(function(req, res) {
// don't reload page
???
// send PUT :username user to current users following array
...
});
So you're on the right track, but instead of putting your actions in the HTML (in your jade file) you're gonna have to add a script section to your jade and use javascript to attach an onClick event to the button so that when you press the button you invoke your ajax method.
Let me know if that doesn't make sense.

res.send() express.js automatically redirect

I am using nodejs and the framework express.js to realize my website.
I am submitting a POST request on an url (/report/reportname) reportname is a variable.
so I do this :
app.post('/report/:id', function(req, res){
var id=req.param('id');
var bodyreportHtml;
go.prototype.runReport(id,res);
}
The thing is that in go.prototype.runReport(id,res)
I do a res.send(bodyofthereport).
So when I click on submit on my form that just redirect me on /report/nameofthereport where the pdf report is.
Everything is working but I would like to put this url /report/nameofthereport (the pdf report) in an iframe.
So when I submit the post request I want it just refresh the iframe and print the report in it ( the iframe is on the same page than the form).
But the res.send(bodyofthereport) is essential : it prints my report at /report/nameofthereport
And I can't do a res.redirect('/') because the body is finished
How can I do ?
Thanks !
If you want to POST to an iframe, you could just set the target attribute of the form to the name of the iframe:
<form action='/report/ID' method='POST' target='FOO'></form>
<iframe name='FOO'></iframe>
Nothing node.js or Express specific about this!

Resources