【问题标题】:Saving data to json using nodejs and cointicker使用 nodejs 和 cointicker 将数据保存到 json
【发布时间】: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


【解决方案1】:

这是因为 cointicker 在 then 中返回 json,所以当您执行 res.status(200).json(posts.data); 时,它返回未定义。只需用 res.status(200).json(posts) 替换它,它应该可以工作

你也不能这样做router.get((req, res) => { 在此之前您需要一条路径。我试过这段代码 router.get('/convert', (req, res) => { 并通过上面的更改工作

【讨论】:

  • 感谢您的帮助,但它不起作用。 html 和控制台不显示任何信息。这是我尝试遵循的教程:scotch.io/tutorials/mean-app-with-angular-2-and-the-angular-cli 如果我逐步遵循该示例,它可以工作,但当我尝试使用 cointicker 时则不行.
  • 好吧,如果您在前缀中添加“/change”,那么当您调用它时,需要使用 url“/api/convert”来调用它。要检查您的服务器是否在终端中工作,只需编写 curl "localhost:3000/api/convert"(使其使用正确的端口而不是 3000)并查看您是否得到正确的响应,或者您可以转到页面“localhost:3000/api/convert”
猜你喜欢
  • 2020-08-02
  • 2019-11-03
  • 1970-01-01
  • 2015-05-21
  • 2020-12-26
  • 2017-05-12
  • 2015-06-18
  • 2021-12-18
  • 2020-01-19
相关资源
最近更新 更多