2017-03-03 16 views
3

Server.jsTypeError例外:

const express = require('express'); 
const bodyParser = require('body-parser'); 
const app = express(); 

// server port is 3000 
let port = 3000; 

// use bodyParser.json and urlencoded 
app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({ 
    extended: true, 
})); 

// use api/v1, require routes/app.js 
app.use('/api/v1', require('./routes/app.js')(express)); 

exports.server = app.listen(port,() => { 
    console.log('Server active on port', port); 
}); 

app.js

// require url shortener 
const shurl = require('../modules/shurl'); 

module.exports = (express) => { 
    const router = express.Router(); 

    router.get('/status', (req, res) => { 
    res.json({ 
     healthy: true, 
    }) 
    }); 

    router.post('/urls', (req, res) => { 
     res.send(shurl(req, res)); 
    }); 

    return router; 
} 

shurl.jsキー新しいHMAC(:91 16 crypto.js)でのバッファでなければなりません

const crypto = require('crypto'); 

module.exports = (url, res) => { 
    // set the shortened url prefix 
    let prefix = 'shurl.io/'; 
    // get the url data 
    let hashUrl = url.body.url; 
    // create the hash 
    let hash = crypto.createHmac('sha256', hashUrl).digest('hex'); 
    // shorten the hash length to 7 
    hashUrl = hash.substr(0,7); 
    // create the shortened url 
    let shortened = prefix + hashUrl; 
    // send the shortened url 
    res.json({shortUrl: shortUrl}); 
} 

エラー:

 
TypeError: Key must be a buffer 
    at new Hmac (crypto.js:91:16) 
    at Object.Hmac (crypto.js:89:12) 
    at module.exports (C:\xampp\htdocs\url-shortener\src\modules\shurl.js:16:21) 
    at router.post (C:\xampp\htdocs\url-shortener\src\routes\app.js:21:16) 
    at Layer.handle [as handle_request] (C:\xampp\htdocs\url-shortener\node_modules\express\lib\router\layer.js:95:5) 
    at next (C:\xampp\htdocs\url-shortener\node_modules\express\lib\router\route.js:131:13) 
    at Route.dispatch (C:\xampp\htdocs\url-shortener\node_modules\express\lib\router\route.js:112:3) 
    at Layer.handle [as handle_request] (C:\xampp\htdocs\url-shortener\node_modules\express\lib\router\layer.js:95:5) 
    at C:\xampp\htdocs\url-shortener\node_modules\express\lib\router\index.js:277:22 
    at Function.process_params (C:\xampp\htdocs\url-shortener\node_modules\express\lib\router\index.js:330:12) 

このエラーを引き起こしていると誰もが修正を知っている正確に何を? let hashUrl = url.body.url;let hashUrl = url.body.url.toString();する必要があります:私は短縮URLを作成するために、POSTしようとするとエラーがshurl.js

ラインから来ている127.0.0.1:3000/api/v1/urls

+0

すべき

またはラインlet hash = crypto.createHmac('sha256', hashUrl).digest('hex'); 問題は解決された。 私は同じような状況にあります – visrey

答えて