使用node.js调用apis像chargebee

当涉及到通过node.js调用API时,我有点困惑。 我有一个运行node js的服务器,我可以安装类似于chargebee的框架。

我创build了一个HTML页面,我订阅等现在,我想打电话给相应的收费function,使订阅。 如果我尝试加载chargebee require('chargebee')则失败。 我只能在服务器js中加载它。

那么我怎样才能使用chargebee的function呢?

是否有可能通过单击button从chargbee调用函数? 我必须通过快递来提供这个function吗?

当我谈到node.js时,我想我不明白客户端代码和服务器端代码之间的区别。 例如,如何通过点击htmlbutton来调用服务器端的function?

为了触发来自客户端的请求,你可以使用表单或AJAX。 这里是一个快速框架的例子,其中表单用于触发请求并在chargebee中创build订阅

客户端代码:

 <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> 

节点 – 服务器代码:

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