我是Node js的新手,仍然在学习它。我正在使用NodeJS和ExpressJS构建REST API,并在通过ExpressJS设置OAuth 1.0时遇到问题。我的要求是从API获取一些数据并将其发布。我具有以下OAuth 1.0授权信息:
我遇到了ouath-request,oauth-shim,oauth-signature,却不确定要正确使用哪一个。
此外,我的API网址很少,例如,
URL:https://developer.shilpe.com/rest/V1/products/FS01(获取方法-通过ID FS01获取产品)
URL:https://developer.shilpe.com/rest/V1/products(获取方法-获取所有产品)
以下是我的代码:
const express = require('express');
const bodyParser = require('body-parser');
const crypto = require('crypto');
//const request = require('request');
//const OAuth = require('oauth-1.0a');
const OAuth = require('oauth-request'); //for now im trying with this
//const oauthshim = require('oauth-shim');
//const OAuth = require('oauth-signature');
const config = require('./config'); //I have a config.js file which stores all the keys and tokens
const server = express();
server.use(bodyParser.urlencoded({ extended: true }));
server.use(express.json());
//here i need to use one of the oauth packages, for now im using oauth-request
const shilpe = OAuth({
consumer:
{
key: config.MAGENTO.consumerKey,
secret: config.MAGENTO.consumerSecret
},
signature_method: 'HMAC-SHA1',
hash_function(base_string, key)
{
return crypto.createHmac('sha1', key).update(base_string).digest('base64');
}
});
shilpe.setToken({
key: config.MAGENTO.tokenKey,
secret: config.MAGENTO.tokenSecret
});
//post using expressJS
server.post('/get-shilpe-products', (req, res) => {
console.log(" -> Server log : get-shilpe-product API request");
//here i will call my url and process with my function
const URL = 'https://developer.shilpe.com/rest/V1/products/FS01';
shilpe.get({
url: URL,
json: true
}, function(err, res, products) {
console.log("result: " + products);
});
});
//My port
const port = process.env.PORT || 8000;
server.listen(port, () => console.log(`Server is up and running on port ${port}...`));
该程序的输出:
具有oauth授权的API网址的邮递员输出: