【发布时间】:2017-12-20 03:25:05
【问题描述】:
我正在学习 nodejs,我正在创建一个服务器来使用名为 Coin-Ticker 的 npm 获取加密货币的价格。我想使用我在 Angular 应用程序中获取的数据,但它没有在 html 中显示数据。这是我的代码:
server.js
const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');
const coinTicker = require('coin-ticker');
const api = require('./server/routes/api');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'dist')));
app.use('/api', api);
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
const port = process.env.PORT || '3000';
app.set('port', port);
const server = http.createServer(app);
server.listen(port, () => console.log(`API running on localhost:${port}`));
API.JS
const express = require('express');
const router = express.Router();
const coinTicker = require('coin-ticker');
/* GET api listing. */
router.get('/', (req, res) => {
res.send('api works');
});
router.get((req, res) => {
coinTicker('bitfinex', 'BTC_USD')
.then(posts => {
res.status(200).json(posts.data);
})
.catch(error => {
res.status(500).send(error)
});
});
module.exports = router;
感谢您的帮助!
【问题讨论】:
-
您在控制台中遇到什么错误?来自终端的任何日志?你的 index.html 中有什么?
router.get((req, res) => {似乎也错了……我认为您需要一条路径作为第一个参数。 -
感谢您的回复@lxe。终端根本没有日志,html 只是接收数据。我试着按照这个例子:scotch.io/tutorials/mean-app-with-angular-2-and-the-angular-cli
-
客户端和服务器是独立的应用程序。确定您的服务器应用程序是否返回预期的数据。如果是这样,那么您的问题出在客户端应用程序中。
标签: javascript json node.js angular bitcoin