Render view as result of POST request in Express - node.js

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});
});

Related

Express js - how to redirect to new page with new data

Im on the home page and i see a list of names. When I click a name, a post request is sent to the backend. From here, I want to one: load the respective profile data from the database, and two: redirect to the profile page and display that data.
From the research i've done, it seems like I have to create an http session variable and decorate that with my profile data before redirecting to the profile page. Is that the best way to go about this?
my html:
<div class="result" onclick="loadProfile(this)" onmouseover="showActions(this)" onmouseleave="removeActions(this)">
<p id="user-id" style="display:none;"> 123456 </p>
<div class="person-info">
</div>
</div>
my front-end js:
function loadProfile() {
}
how would i write the get request? and send the id as a param?
Querying data should be a GET request, not a POST request. A POST would typically be for adding a new record or in some cases, modifying a record. A GET is for querying existing data. As such, you should be constructing a URL such as:
/profile?id=someName
And doing a GET request. Then you create a route handler for /profile on your server (or whatever you want the URL to be named) and that route handler parses the id value out of the query string in the URL. If you're using request, it would be in req.query.id.
Then, that route handler can use the id value to query the data store and show the appropriate profile page.
No session is needed. No redirect is needed. This is stateless (which is desirable from an http server point of view). Note, this also creates a URL structure where a user can bookmark the profile page or you can link to it directly in HTML.
If you show the client-side HTML/code that is creating your current request, we could advise more specifically on how to create the GET request from it. If you're using an HTML <form>, you can configure the form to create a GET request instead of the POST and to put the data into the query string.
In loadProfile(), you can just construct the URL by fetching the current ID based on the value of this and then just do in loadProfile():
let id = <code to get id from the current HTML, based on the click>
let newURL = `/profile?id=${id}`;
window.location = newURL; // will cause browser to go to that page
Then, construct the appropriate route on the server to handle this URL.

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' });
});

External web service redirects the user and posts data to my callback URL. How do I render the posted data to the user in an Express/Next.js app?

Any help would be hugely appreciated! Been stuck on this for a few days.
I have an Express/Next.js app where:
I send the user to an external website
user makes a payment
external website redirects and posts data back to my callback URL.
So now I have the user on a mysite.com/payment-complete route but also want to display the data that was sent back.
I have an app.post endpoint to successfully grab the data:
app.post("/payment-complete", async (req, res) => {
const transactionID = req.body.trans_id;
});
How would I pass the data to the user who is already on that route? Or pass the data before the page is rendered?
The flow of data is third party > my server > user and I'm not sure how to make this work.
I'd be grateful for any help/direction with this.
If anyone comes across this - the problem was that in Express (and other languages) you can't redirect or render a view for an AJAX POST request but you can if the POST request is coming from a submitted html form. The web service was in fact POST-ing the data and redirecting my users with a form and so I could render a view.
Following code worked using Handlebars templating engine to send the render.
router.post("/payment-ok", async (req, res) => {
const transactionID = req.body.trans_id;
return res.render("rendertest", { id: transactionID });
});
Should also possibly work with app.render to send a Next.js view instead, but I wanted to render from a separate routes file.

How to "catch" a form's post request status?

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
});

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.

Resources