Coinkite,Node.js授权失败,不知道为什么

时间:2015-04-17 06:29:04

标签: javascript node.js asp.net-web-api

当我尝试使用api ket off http://forecast.io/下面的代码时,它有效。但是当我通过https://coinkite.com/尝试它时,我得到了401未经授权的例外。

我不明白为什么不经历。我有一个单独的项目文件,它运行类似的coinkite代码,但它是一个命令行应用程序,它给了我正确的响应。

这是执行的主要内容,

/*global require*/
/*global console*/
/*global process*/
/*jslint nomen: true*/
/*global __dirname*/
/*jslint nomen: false*/

// Dependancies
var bodyParser = require('body-parser');
var express = require('express');
var path = require('path');

// Express
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var currentPort = process.env.PORT || 3000;
app.set('port', currentPort);

   // Here you set that all templates are located in `/views` directory
   /*jslint nomen: true*/
   app.set('views', path.join(__dirname, 'views'));
   /*jslint nomen: false*/
   app.set('view engine', 'ejs');

   // Routes
   var coinkite = require('./routes/coinkite');

   app.use('/coinkite', coinkite);

   // Start Server
   app.listen(currentPort);
   console.log('Server is running at port: ' + currentPort);

这是coinkite的路线,

/*global require*/
/*global console*/
/*global module*/
/*global process*/
/*global CK_API */

// Dependancies

var express = require('express');
var crypto = require('crypto');
var request = require('request');

var CK_API_KEY = 'XX-XX-XXXX';
var CK_API_SECRET = 'XXXXXXXXXXX';
var CK_ENDPOINT = '/v1/my/self';
var CK_DATA = '';

var router_CK = express.Router();

router_CK.get('/', function (req, res) {
    'use strict';

    var ts = (new Date()).toISOString(),
        sign = CK_ENDPOINT + '|' + ts,
        hm = crypto.createHmac('sha256', CK_API_KEY).update(sign).digest('hex'),
    options = { uri: 'https://api.coinkite.com' + CK_ENDPOINT, headers: { 'X-CK-Key': CK_API_KEY, 'X-CK-Sign': hm, 'X-CK-Timestamp': ts }, json: true};

    request.get(options, function (error, response, body) {
        if (!error && response.statusCode === 200) {
            console.log(body);
            CK_DATA = JSON.parse(body);
            console.log(CK_DATA);
        }
    });

    res.render('coinkite-index', {data: CK_DATA});
});

// Return Router
module.exports = router_CK;

另外,如果我想在Node.js中的模块之间传递变量,我该怎么做?

感谢帮助。

干杯

2 个答案:

答案 0 :(得分:0)

您的代码与官方JS代码from Coinkite github非常相似。

401响应中出现了什么错误消息?这通常非常详细和有用。


后来

再看看你的代码,我现在看到了问题......你有:

    hm = crypto.createHmac('sha256', CK_API_KEY).update(sign).digest('hex'),

但是在那一行,它应该是HMAC中使用的CK_API_SECRET(不是KEY)。

答案 1 :(得分:0)

代码有效,必须为符号传递CK_API_SECRET而不是CK_API_KEY。

hm = crypto.createHmac('sha256', CK_API_KEY).update(sign).digest('hex'),