Calling apis like chargebee with node.js - javascript

I'm a little be confused when it comes to calling APIs over node.js.
I have a server running node js where I can install frameworks like the one for chargebee.
I created a html page where I make subscriptions etc. Now I would want to call the corresponding chargebee function to make the subscription.
If I try to load chargebee with require('chargebee')it failes. I can only load it in the server js.
So how would it be possible for me to use the functionalities of chargebee?
Is it possible that I invoke a function from chargbee by a click on the button? Do i have to provide this function by express?
I think I did not understand the difference between client side code and server side code when it comes to node.js.
How can function on the server side be invoked by clicks on html buttons for example?

In order to trigger request from client side you can use forms or AJAX. Here is an example with express framework in which form is used to trigger request and create subscription in chargebee
Client-Side Code:
<html>
<body>
<form action="/subscribe" method="post">
<label for="name">First Name:</label>
<input type="text" id="name" name="customer[first_name]" placeholder="first name" />
<br />
<label for="name">Last Name:</label>
<input type="text" id="name" name="customer[last_name]" placeholder="last name" />
<br />
<label for="email">Email:</label>
<input type="email" id="email" name="customer[email]" placeholder="Enter your email address" />
<br />
<input type="submit" value="Create Profile" />
</form>
</body>
</html>
Node-Server code:
var express = require('express');
var chargebee = require("chargebee");
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
chargebee.configure({site : "<<site_name>>",
api_key : "<<api_key>>"
app.get('/', function(req, res){
res.sendFile(__dirname + '/form.html');
});
app.post('/subscribe', function(req, res){
var params = req.body;// getting form params as JSON
params['plan_id']='enterprise'; // plan id that is present in your Chargebee site
chargebee.subscription.create(params).request(function(error,result){
if(error){
//handle error
console.log(error);
}else{
console.log(result);
var subscription = result.subscription;
res.writeHead(200, {
'content-type': 'text/plain'
});
res.write('Successfully created subscription\n\n' + 'id :: '+ subscription.id);
res.end();
}
});
});
app.listen(3000);
console.log("server listening on 3000");

It is possible with chargebee v3 . Hope This will solve your query
<!DOCTYPE html>
<html>
<head>
<title>chargebee Example</title>
<script src = "https://js.chargebee.com/v2/chargebee.js" data-cb-site = "your site name" > </script>
</head>
<body>
<!-- for creating subscription -->
<a href="javascript:void(0)" data-cb-type="checkout" data-cb-plan-id="30" >subscribe</a>
<!-- for managing portal -->
<a href="javascript:void(0)" data-cb-type="portal" >Manage account</a>
</body>
</html>

Related

Cannot GET /url error in Node Js Post Handling

I have written this ejs file named Post_handling.ejs:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>POST-Handling Page</title>
</head>
<body>
<h1>Register here!!!</h1>
<form class="" method="POST" action="/Post_handling">
<label for="">City:</label>
<input type="text" name="city" value="">
<label for="">State:</label>
<input type="text" name="state" value="">
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
And I have written this node.js code for handling POST request:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.set('view engine', 'ejs');
app.post('/Post_handling', urlencodedParser, function(request, response){
response.render('Post_handling');
console.log(request.body);
});
app.listen('3000');
console.log('Hello user! Now you are listening on port 3000 at address 127.0.0.1:3000\nPress ctrl+C to stop.');
When I run the node.js code, then I get this error:
Cannot GET /Post_handling
app.listen('3000');
Are you accessing correct port ? Try to specify full url (with port)
You are using POST method in your code, but trying to access it with GET method ? Try this:
app.get('/Post_handling', urlencodedParser, function(request, response){
response.render('Post_handling');
console.log(request.body);
});

Having an issue with processing post request in node.js

Having an issue with processing post request in node.js and it is showing the error: Cannot POST /index.html
Since body-parser is deprecated, I am stuck with this error
const express = require("express");
const app = express();
app.use(express.json({ limit: '50mb' }));
app.get("/", function(req, res){
res.sendFile(__dirname+"/index.html");
});
app.post("/", function(req, res){
var num1 = Number(req.body.num1);
var num2 = Number(req.body.num2);
var result = num1+num2;
res.send(String(result));
});
app.listen(3000, function(){
console.log("Server is running on port 3000");
});
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1>Calculator</h1>
<form action="index.html" method="post">
<input type="text" name="num1" placeholder="First Number">
<input type="text" name="num2" placeholder="Second Number">
<button type="submit" name="submit">Calculate</button>
</form>
</body>
</html>
I don't get it. What is your requirement with these code snippets?
Since body-parser is deprecated, I am stuck with this error
body-parser is now part of Express and you can just get it by writing,
app.use(express.urlencoded({ extended: false }));
error: Cannot POST /index.html
The reason Express throw this error is because, you don't have matching POST route. Instead you have POST / route. I would suggest you to update the <form>'s action to / instead of index.html.
<form action="/" method="post">
<input type="text" name="num1" placeholder="First Number" />
<input type="text" name="num2" placeholder="Second Number" />
<button type="submit" name="submit">Calculate</button>
</form>

Passing values from a view to Node without URL in Nodejs

I am using nodejs with express and ejs.
Every one on internet ask how to pass value from node to the view, but what about the opposite?
For example, I ask my user to input a string in a form, when the user clicks the button, how can I get this string without passing it as a parameter in the url?
The form:
<div class="container">
<form style="width:50%">
<div class="form-group">
<label for="text">Name of the product</label>
<input type="text" class="form-control" id="pName">
</div>
<div class="form-group">
<label for="text">Reciever</label>
<input type="text" class="form-control" id="reciever">
</div>
<div class="form-group">
<label for="text">Location</label>
<input type="text" class="form-control" id="location">
</div>
<!-- <div class="checkbox">
<label><input type="checkbox"> Remember me</label>
</div>-->
<button type="submit" class="btn btn-default">Submit</button>
</form>
The app.js
var express = require('express');
var app = express();
//ALL GLOBAL VARIABLES
var port = 8080;
app.get('/', function(req, res) {
res.render('index.ejs');
});
app.get('/barcode', function(req,res) {
res.render('barcode.ejs');
});
app.listen(port);
I know I can do this:
app.get('/url/:parameter', function(req.res) {
var foo = req.params.parameter;
}
But if I don't want to use the URL, is it possible to retrieve the data?
Use POST as a method for your html form
<form action="/myapi" method="post">
<input type="text" class="form-control" id="pName" name="pName">
<button type="submit" class="btn btn-default">Submit</button>
</form>
And then handle the client form "action" with app.post on the back end
app.post('/myapi', function(req, res) {
res.send('The pName is "' + req.body.pName + '".');
});
You can use POST method instead of GET. You need to change the route in your Express to
app.post('/url', function(req.res))
and add a method on your form
<form style="width:50%" method="POST">
If you use a POST request the parameters are not part of the URL. E.g.
app.post('/path', function(req, res) {
...
//You can retrieve the parameters of the POST request here
]);
You'll need the body-parser module to be able to get the POST parameters. Here's an answer about how to get the POST parameters once you've set up the route.
Your form should have a method and and action:
<form action="/path" method="POST">...</form>
From your question, In general if you want to get a value from the unique id, you will store that value as a global variable. so you can easily get the current user and user related details.

Displaying data from node.js server to html page

I am trying to show my form data to another html page. This is my server.js
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var path=require('path');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, '/')));
app.post('/myaction.html', function(req, res) {
res.send('You sent the name "' + req.body.name + '".');
});
app.listen(8080, function() {
console.log('Server running at http://127.0.0.1:8080/');
});
And this is my 'index.html'
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Demo Form</title>
</head>
<body>
<div id="contact">
<h1>Enter the values</h1>
<form action="/myaction.html" method="post">
<fieldset>
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="Enter your full name" />
<label for="email">Email:</label>
<input type="email" id="email" placeholder="Enter your email address" />
<label for="message">Message:</label>
<textarea id="message" placeholder="What's on your mind?"></textarea>
<input type="submit" value="Send message" />
</fieldset>
</form>
</div>
</body>
</html>
Now, it is working properly and the name is reflecting in the myaction.html page. But I want to stylize the 'myaction.html' page a bit and make it look more presentable. Is there any way to add more html tags and text to the page or to display the form data in an already existing page?
Use a template engine. A good one is EJS. First you have to use npm install ejs and then app.set('view engine', 'ejs'); inside your server.js . After that you will be able to create a new folder in your project named views and inside you can create index.ejs and other views files. Inside your server.js you can use res.render('index.ejs', {data: aJavascriptVariable, data1: moreVars}); . Finally to use this variables inside the .ejs files you can use <%= data %> or <%= data1 %>. Of course html can be written inside a .ejs file.

HTML form to POST data to MySQL

I'm trying to post data to an MySQL database by using Node.js.
This is my htmlHTML form:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>form</title>
</head>
<body>
<h1>This is my form</h1>
<!-- local host to be changed? -->
<form action="http://localhost:3000/index.html" method="POST">
First name:<br>
<input type="text" name="firstname" value="John">
<br>
Last name:<br>
<input type="text" name="lastname" value="Doe">
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
And here is my MySQL.js:
var mysql = require('mysql');
var connection = mysql.createConnection(
{
host : 'mysqlhost',
port : '3306',
user : 'myuser',
password : 'mypassword',
database : 'myuser'
} ); connection.connect(); var query = connection.query('SELECT * FROM http://localhost:3000/index.html');
query.on('error', function(err) {
throw err; });
query.on('fields', function(fields) {
console.log(fields); })
query.on('result', function(row) {
console.log(row); }); connection.end();
Is this even possible?
Yes, this is possible, but you're definitely not going into the right direction. I suggest learning how to make a simple REST API Node app to get started. This tutorial is a good starting point. I suggest using Express as it simplifies the task of handling POST/GET requests.
Here is starter code that does what you want.
index.html
Note how I used /data instead of localhost:3000/index.html in the <form action=...> part. This is generally known as a REST api.
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>form</title>
</head>
<body>
<h1>This is my form</h1>
<!-- local host to be changed? -->
<form action="/data" method="POST">
First name:<br>
<input type="text" name="firstname" value="John">
<br>
Last name:<br>
<input type="text" name="lastname" value="Doe">
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
app.js
var app = require('express')();
var bodyParser = require('body-parser');
var path = require('path');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.post('/data', function(req, res) {
console.log(req.body.firstname);
console.log(req.body.lastname);
// Add these values to your MySQL database here
});
app.listen(3000);
File structure
app.js
index.html
Commands to run
npm install express
npm install body-parser
node app.js
Then simply go to localhost:3000 in your browser.

Categories