如何从节点服务器获取数据

时间:2019-08-18 00:55:16

标签: node.js reactjs

我是新来的反应者,我正在尝试构建一个简单的应用来检索股票价格。

我可以到达所需的服务器路由,但是从服务器获取FetchError: invalid json response body,这是什么意思?我应该如何在我的快速路由中正确获取外部api并将该数据作为响应发送?

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  state = {
    response: '',
    symbol: '',
  };

  handleSubmit = async e => {
    e.preventDefault();
    let apiURL = `/stocks/${ this.state.symbol }/price`
    fetch(apiURL)
      .then(res => res.json())
      .then( (result) => {
        this.setState({
          response: result
        })
      })
  };

render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
        </header>

        <form onSubmit={this.handleSubmit}>
          <input
            type="text"
            value={this.state.symbol}
            onChange={e => this.setState({ symbol: e.target.value })}
          />
          <button type="submit">Submit</button>
        </form>
        <p>{this.state.response}</p>
      </div>
    );
  }
}

export default App;

server.js

const express = require('express')
const path = require('path')
const bodyParser = require('body-parser')
const fetch = require('node-fetch');

const app = express()
const port = process.env.PORT || 5000

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))

// API routes
app.get('/stocks/:symbol/price', (req, res) => {
  const token = 'pk_5f69bda1e3074237a9d2e844a3dafbff'
  const symbol = req.params.symbol
  const apiURL = `https://sandbox.iexapis.com/stable/stock/${symbol}/price?token=${token}`

  fetch(apiURL)
    .then(res => res.json())
    .then(data => {
      res.send({ data })
    })
})

app.listen(port, () => console.log(`Listening on port ${port}`))

package.json

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "axios": "^0.19.0",
    "body-parser": "^1.18.3",
    "express": "^4.16.4",
    "node-fetch": "^2.6.0",
    "react": "^16.9.0",
    "react-dom": "^16.9.0",
    "react-scripts": "0.9.x"
  },
  "devDependencies": {
    "concurrently": "^4.0.1",
    "nodemon": "^1.9.2",
    "ws": "3.3.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject",
    "client": "yarn start",
    "server": "nodemon server.js",
    "dev": "concurrently --kill-others-on-fail \"yarn server\" \"yarn client\""
  },
  "proxy": "http://localhost:5000/"
}

0 个答案:

没有答案