导致CORS错误的区块链API调用

时间:2019-03-15 17:39:55

标签: reactjs express cors

我在ReactJS中构建一个应用程序,似乎遇到了障碍。当我使用CORS-Anywhere插件(Chrome和FF)时,会出现来自Blockchain的数据,但是,如果没有此插件,则不会显示任何内容。我知道这与我的server.js文件中的get请求和客户端的获取有关,但是我似乎无法弄清楚我在做什么错。

请参阅所附的屏幕截图:

CORS Errors

CORS-Anyhere Disabled

CORS-Anywhere Enabled - Data Displayed

server.js

const express = require('express');
const app = express();
const path = require('path');
const port = process.env.PORT || 5000;
const axios = require('axios');

app.use(express.static(path.join(__dirname, '/build')));

const getSingle = async () => {
  try {
    return await axios.get('https://blockchain.info/rawblock/0000000000000bae09a7a393a8acded75aa67e46cb81f7acaa5ad94f9eacd103');
  } catch (error) {
    console.log(error);
  }
}


const getTrans = async () => {
  try {
    return await axios.get('https://blockchain.info/rawtx/b6f6991d03df0e2e04dafffcd6bc418aac66049e2cd74b80f14ac86db1e3f0da');
  } catch (error) {
    console.log(error);
  }
}


const getLatest = async () => {
  try {
    return await axios.get('https://blockchain.info/latestblock');
  } catch (error) {
    console.log(error);
  }
}

//build mode
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname+'/build/index.html'));
})

app.get('/singleblock', function (res, req) {
   getSingle()
   .then(response => {
      if (response.data.message) {
         res.status(200).send(response.data.message);
      }
      else {
         res.status(500).send('Failed to fetch latest Blockchain...');
      }
   })
   .catch(error => {
      console.error(error);
   });
});

app.get('/transblock',function (res, req) {
   getTrans()
   .then(response => {
      if (response.data.message) {
         res.status(200).send(response.data.message);
      }
      else {
         res.status(500).send('Failed to fetch latest Blockchain...');
      }
   })
   .catch(error => {
      console.log(error);
   });
});

app.get('/latestblock', function (res, req) {
   getLatest()
   .then(response => {
     if (response.data.message) {
        res.status(200).send(response.data.message);
     }
      else {
         res.status(500).send('Failed to fetch latest Blockchain...');
      }
   })
   .catch(error => {
      console.log(error);
   });

});

//start server
app.listen(port, (req, res) => {
  console.log( `server listening on port: ${port}`);
})

SingleBlock.js

import React, { Component } from 'react';
export default class SingleBlock extends Component {
  constructor(props) {
    super(props);

    this.state = {
      single: []
    };
  }

  componentDidMount() {
    fetch('https://blockchain.info/rawblock/0000000000000bae09a7a393a8acded75aa67e46cb81f7acaa5ad94f9eacd103')
    // fetch('/singleblock')
    .then(singleblock => {
      return singleblock.json();
    }).then(data => {
      this.setState({single: data});
    })
  }

  render() {
    return (
      <div className="single-block-container">
        <div id="single-block-hash"><strong>Block Hash:</strong> {this.state.single.hash}</div>
        <div id="single-block-ver"><strong>Block Version:</strong> {this.state.single.ver}</div>
        <div id="single-block-prev"><strong>Previous Block:</strong> {this.state.single.prev_block}</div>
        <div id="single-block-mrkl"><strong>Block MRKL_ROOT:</strong> {this.state.single.mrkl_root}</div>
        <div id="single-block-time"><strong>Block Time:</strong> {this.state.single.time}</div>
        <div id="single-block-bits"><strong>Block Bits:</strong> {this.state.single.bits}</div>
        <div id="single-block-nonce"><strong>Block Nonce:</strong> {this.state.single.nonce}</div>
        <div id="single-block-ntx"><strong>Block N_TX:</strong> {this.state.single.n_tx}</div>
        <div id="single-block-size"><strong>Block Size:</strong> {this.state.single.size}</div>
        <div id="single-block-index"><strong>Block Index:</strong> {this.state.single.block_index}</div>
        <div id="single-block-main"><strong>Block Main Chain:</strong> {this.state.single.main_chain}</div>
        <div id="single-block-height"><strong>Block Height:</strong> {this.state.single.height}</div>
        <div id="single-block-rec"><strong>Block Received Time:</strong> {this.state.single.received_time}</div>
        <div id="single-block-relayed"><strong>Block Relayed By:</strong> {this.state.single.relayed_by}</div>
        <div id="single-block-input"><strong>Block Inputs:</strong> {this.state.single.inputs}</div>
        <div id="single-block-output"><strong>Block Outputs:</strong> {this.state.single.out}</div>
      </div>
    )
  }
}

package.json

{
  "name": "chainyard-challenge",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "axios": "^0.18.0",
    "babel": "^6.23.0",
    "babel-preset-es2015": "^6.24.1",
    "body-parser": "^1.18.3",
    "cors": "^2.8.5",
    "express": "^4.16.4",
    "fetch-jsonp": "^1.1.3",
    "http": "0.0.0",
    "middy": "^0.23.0",
    "node": "^11.11.0",
    "react": "^16.8.4",
    "react-dom": "^16.8.4",
    "react-scripts": "2.1.8"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "heroku-postbuild": "npm run build"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "keywords": [
    "node",
    "heroku",
    "express"
  ],
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ]
}

在此先感谢您的输入!

0 个答案:

没有答案