当谈到通过 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/