最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

从node.js传递数据以使用express进行响应

IT培训 admin 5浏览 0评论

从node.js传递数据以使用express进行响应

我正试图在nodejs中调用API(只允许服务器端调用)。我设法将信息恢复到我的控制台,现在我试图将该数据传递给我的反应应用程序的app.js文件。

我目前正在使用react应用程序一个node.js后端并表达它们之间的通信。

我有两个文件夹backendclient

这是backend/server.js

const express = require("express");
const API_PORT = 3001;
const app = express();
const router = express.Router();

  router.get("/bitmex", () => !async function(){
      const api = new BitmexAPI({
        "apiKeyID": "",
        "apiKeySecret": ""
      });
       const chatMessage = await api.Position.get()
       return(chatMessage.json({ success: true, chatMessage}))
  }())

  app.listen(API_PORT, () => console.log(`LISTENING ON PORT ${API_PORT}`));

这是client/App.js

import React, { Component } from "react";


 class App extends Component {
 // initialize our state 
 state = {
    data: [],
 };



 // when component mounts, first thing it does is fetch all existing 
 data in our db
 // then we incorporate a polling logic so that we can easily see if our db has 
 // changed and implement those changes into our UI
 componentDidMount() {
 console.log("this worked successfully")
 this.getDataFromDb();
 }

 getDataFromDb = () => {
     fetch("http://localhost:3001/bitmex")
     .then(data => chatMessage.json())
     .then(res => this.setState({ data: res.data }));
 };




// here is our UI
// it is easy to understand their functions when you 
// see them render into our screen
render() {
const { data } = this.state;
return (
  <div>
    <ul>
      //render data here somehow
    </ul>
  </div>
);
}
}

export default App;

API的响应如下所示:

[
   {
    "account": 0,
    "symbol": "string",
    "currency": "string",
    "underlying": "string",
    "quoteCurrency": "string",
    "commission": 0,
    "initMarginReq": 0,
    "maintMarginReq": 0,
    "riskLimit": 0,
    "leverage": 0,
    "crossMargin": true,
    "deleveragePercentile": 0,
    "rebalancedPnl": 0,
    "prevRealisedPnl": 0,
    "prevUnrealisedPnl": 0,
    "prevClosePrice": 0,
    "openingTimestamp": "2019-02-13T18:37:44.780Z",
    "openingQty": 0,
    "openingCost": 0,
    "openingComm": 0,
    "openOrderBuyQty": 0,
    "openOrderBuyCost": 0,
    "openOrderBuyPremium": 0,
    "openOrderSellQty": 0,
    "openOrderSellCost": 0,
    "openOrderSellPremium": 0,
    "execBuyQty": 0,
    "execBuyCost": 0,
    "execSellQty": 0,
    "execSellCost": 0,
    "execQty": 0,
    "execCost": 0,
    "execComm": 0,
    "currentTimestamp": "2019-02-13T18:37:44.780Z",
    "currentQty": 0,
    "currentCost": 0,
    "currentComm": 0,
    "realisedCost": 0,
    "unrealisedCost": 0,
    "grossOpenCost": 0,
    "grossOpenPremium": 0,
    "grossExecCost": 0,
    "isOpen": true,
    "markPrice": 0,
    "markValue": 0,
    "riskValue": 0,
    "homeNotional": 0,
    "foreignNotional": 0,
    "posState": "string",
    "posCost": 0,
    "posCost2": 0,
    "posCross": 0,
    "posInit": 0,
    "posComm": 0,
    "posLoss": 0,
    "posMargin": 0,
    "posMaint": 0,
    "posAllowance": 0,
    "taxableMargin": 0,
    "initMargin": 0,
    "maintMargin": 0,
    "sessionMargin": 0,
    "targetExcessMargin": 0,
    "varMargin": 0,
    "realisedGrossPnl": 0,
    "realisedTax": 0,
    "realisedPnl": 0,
    "unrealisedGrossPnl": 0,
    "longBankrupt": 0,
    "shortBankrupt": 0,
    "taxBase": 0,
    "indicativeTaxRate": 0,
    "indicativeTax": 0,
    "unrealisedTax": 0,
    "unrealisedPnl": 0,
    "unrealisedPnlPcnt": 0,
    "unrealisedRoePcnt": 0,
    "simpleQty": 0,
    "simpleCost": 0,
    "simpleValue": 0,
    "simplePnl": 0,
    "simplePnlPcnt": 0,
    "avgCostPrice": 0,
    "avgEntryPrice": 0,
    "breakEvenPrice": 0,
    "marginCallPrice": 0,
    "liquidationPrice": 0,
    "bankruptPrice": 0,
    "timestamp": "2019-02-13T18:37:44.781Z",
    "lastPrice": 0,
    "lastValue": 0
  }
]

我希望获得在react应用程序中呈现的API返回的信息。

回答如下:

尝试更改后端脚本以包含正文解析器

// backend/server.js
import express from 'express';
import bodyParser from 'body-parser';
// Set up the express app
const app = express();
const API_PORT = 3001;
// Parse incoming requests data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));


app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
 next();
});

app.get("/bitmex", () => !async function(){
      const api = new BitmexAPI({
        "apiKeyID": "",
        "apiKeySecret": ""
      });
       const chatMessage = await api.Position.get()
       return(chatMessage.json({ success: true, chatMessage}))
  }())

  app.listen(API_PORT, () => console.log(`LISTENING ON PORT ${API_PORT}`));

从node.js传递数据以使用express进行响应

我正试图在nodejs中调用API(只允许服务器端调用)。我设法将信息恢复到我的控制台,现在我试图将该数据传递给我的反应应用程序的app.js文件。

我目前正在使用react应用程序一个node.js后端并表达它们之间的通信。

我有两个文件夹backendclient

这是backend/server.js

const express = require("express");
const API_PORT = 3001;
const app = express();
const router = express.Router();

  router.get("/bitmex", () => !async function(){
      const api = new BitmexAPI({
        "apiKeyID": "",
        "apiKeySecret": ""
      });
       const chatMessage = await api.Position.get()
       return(chatMessage.json({ success: true, chatMessage}))
  }())

  app.listen(API_PORT, () => console.log(`LISTENING ON PORT ${API_PORT}`));

这是client/App.js

import React, { Component } from "react";


 class App extends Component {
 // initialize our state 
 state = {
    data: [],
 };



 // when component mounts, first thing it does is fetch all existing 
 data in our db
 // then we incorporate a polling logic so that we can easily see if our db has 
 // changed and implement those changes into our UI
 componentDidMount() {
 console.log("this worked successfully")
 this.getDataFromDb();
 }

 getDataFromDb = () => {
     fetch("http://localhost:3001/bitmex")
     .then(data => chatMessage.json())
     .then(res => this.setState({ data: res.data }));
 };




// here is our UI
// it is easy to understand their functions when you 
// see them render into our screen
render() {
const { data } = this.state;
return (
  <div>
    <ul>
      //render data here somehow
    </ul>
  </div>
);
}
}

export default App;

API的响应如下所示:

[
   {
    "account": 0,
    "symbol": "string",
    "currency": "string",
    "underlying": "string",
    "quoteCurrency": "string",
    "commission": 0,
    "initMarginReq": 0,
    "maintMarginReq": 0,
    "riskLimit": 0,
    "leverage": 0,
    "crossMargin": true,
    "deleveragePercentile": 0,
    "rebalancedPnl": 0,
    "prevRealisedPnl": 0,
    "prevUnrealisedPnl": 0,
    "prevClosePrice": 0,
    "openingTimestamp": "2019-02-13T18:37:44.780Z",
    "openingQty": 0,
    "openingCost": 0,
    "openingComm": 0,
    "openOrderBuyQty": 0,
    "openOrderBuyCost": 0,
    "openOrderBuyPremium": 0,
    "openOrderSellQty": 0,
    "openOrderSellCost": 0,
    "openOrderSellPremium": 0,
    "execBuyQty": 0,
    "execBuyCost": 0,
    "execSellQty": 0,
    "execSellCost": 0,
    "execQty": 0,
    "execCost": 0,
    "execComm": 0,
    "currentTimestamp": "2019-02-13T18:37:44.780Z",
    "currentQty": 0,
    "currentCost": 0,
    "currentComm": 0,
    "realisedCost": 0,
    "unrealisedCost": 0,
    "grossOpenCost": 0,
    "grossOpenPremium": 0,
    "grossExecCost": 0,
    "isOpen": true,
    "markPrice": 0,
    "markValue": 0,
    "riskValue": 0,
    "homeNotional": 0,
    "foreignNotional": 0,
    "posState": "string",
    "posCost": 0,
    "posCost2": 0,
    "posCross": 0,
    "posInit": 0,
    "posComm": 0,
    "posLoss": 0,
    "posMargin": 0,
    "posMaint": 0,
    "posAllowance": 0,
    "taxableMargin": 0,
    "initMargin": 0,
    "maintMargin": 0,
    "sessionMargin": 0,
    "targetExcessMargin": 0,
    "varMargin": 0,
    "realisedGrossPnl": 0,
    "realisedTax": 0,
    "realisedPnl": 0,
    "unrealisedGrossPnl": 0,
    "longBankrupt": 0,
    "shortBankrupt": 0,
    "taxBase": 0,
    "indicativeTaxRate": 0,
    "indicativeTax": 0,
    "unrealisedTax": 0,
    "unrealisedPnl": 0,
    "unrealisedPnlPcnt": 0,
    "unrealisedRoePcnt": 0,
    "simpleQty": 0,
    "simpleCost": 0,
    "simpleValue": 0,
    "simplePnl": 0,
    "simplePnlPcnt": 0,
    "avgCostPrice": 0,
    "avgEntryPrice": 0,
    "breakEvenPrice": 0,
    "marginCallPrice": 0,
    "liquidationPrice": 0,
    "bankruptPrice": 0,
    "timestamp": "2019-02-13T18:37:44.781Z",
    "lastPrice": 0,
    "lastValue": 0
  }
]

我希望获得在react应用程序中呈现的API返回的信息。

回答如下:

尝试更改后端脚本以包含正文解析器

// backend/server.js
import express from 'express';
import bodyParser from 'body-parser';
// Set up the express app
const app = express();
const API_PORT = 3001;
// Parse incoming requests data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));


app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
 next();
});

app.get("/bitmex", () => !async function(){
      const api = new BitmexAPI({
        "apiKeyID": "",
        "apiKeySecret": ""
      });
       const chatMessage = await api.Position.get()
       return(chatMessage.json({ success: true, chatMessage}))
  }())

  app.listen(API_PORT, () => console.log(`LISTENING ON PORT ${API_PORT}`));
发布评论

评论列表 (0)

  1. 暂无评论