【发布时间】:2017-07-22 23:40:28
【问题描述】:
Server.js
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
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:键必须是缓冲区 在新的 Hmac (crypto.js:91:16) 在 Object.Hmac (crypto.js:89:12) 在 module.exports (C:\xampp\htdocs\url-shortener\src\modules\shurl.js:16:21) 在 router.post (C:\xampp\htdocs\url-shortener\src\routes\app.js:21:16) 在 Layer.handle [as handle_request] (C:\xampp\htdocs\url-shortener\node_modules\express\lib\router\layer.js:95:5) 在下一个(C:\xampp\htdocs\url-shortener\node_modules\express\lib\router\route.js:131:13) 在 Route.dispatch (C:\xampp\htdocs\url-shortener\node_modules\express\lib\router\route.js:112:3) 在 Layer.handle [as handle_request] (C:\xampp\htdocs\url-shortener\node_modules\express\lib\router\layer.js:95:5) 在 C:\xampp\htdocs\url-shortener\node_modules\express\lib\router\index.js:277:22 在 Function.process_params (C:\xampp\htdocs\url-shortener\node_modules\express\lib\router\index.js:330:12)究竟是什么导致了这个错误,有人知道修复方法吗?当我尝试 POST 以创建缩短的 url @ 127.0.0.1:3000/api/v1/urls 时出现此错误
【问题讨论】:
-
很想知道问题是否解决了。我也有类似情况
标签: node.js