javascript - 使用 node.js 调用 chargebee 之类的 api

标签 javascript node.js

当谈到通过 node.js 调用 API 时,我有点困惑。 我有一台运行 node js 的服务器,我可以在其中安装 chargebee 之类的框架。

我创建了一个 html 页面,用于订阅等。现在我想调用相应的 chargebee 函数来进行订阅。 如果我尝试使用 require('chargebee') 加载 chargebee,它会失败。我只能在服务器js中加载它。

那么我怎么可能使用chargebee的功能呢?

是否可以通过单击按钮从 chargbee 调用函数?我必须通过 express 提供此功能吗?

当涉及到 node.js 时,我认为我不理解客户端代码和服务器端代码之间的区别。 例如,如何通过单击 html 按钮来调用服务器端的功能?

最佳答案

为了从客户端触发请求,您可以使用表单或 AJAX。这是一个express框架的例子,其中表单用于触发请求并在chargebee中创建订阅

客户端代码:

<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 服务器代码:

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

关于javascript - 使用 node.js 调用 chargebee 之类的 api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34360486/

相关文章:

node.js - 从服务器端调用 API 需要服务名称作为 API 主机,但在客户端上无法访问

javascript - 如何断言 process.stderr 输出?

javascript - ko observableArray 更新,但绑定(bind)选择列表未更新

javascript - 向表条目添加超链接

JavaScript:将变量插入数组

javascript - Aurelia 中的递归组合元素

javascript - `return await` 是否存在性能问题?

node.js - 发送响应后删除临时文件的正确方法

javascript - Aurelia Babel 未知选项 base.modules 错误

javascript - 如何允许用户在 Node JS Passport JS 失败后尝试使用不同的电子邮件?