重构反应/节点处理响应的方式

时间:2019-08-19 00:53:33

标签: javascript node.js reactjs

我正在使用React前端并从节点服务器中获取数据。我觉得我的代码看起来有点多余,是否有更好的方法来重构所有这些内容?

App.js

  searchStock = async (value) => {
    let priceURL = `/stock/${ value }/price`
    // fetch price data
    fetch(priceURL)
      .then(res => {
        if (res.ok) {
          res.json()
          .then( (result) => {
            this.setState({
              price: result
            })
          })
        }
        else {
          console.log("Something went wrong...")
        }
      })
     }

server.js

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

  fetch(apiURL)
    .then(response => {
      console.log(response.status)
      if (response.ok) {
        response.json().then((data) => {
          res.json(data)
        });
      }
      else {
        res.sendStatus(response.status)
      }
    })
    .catch(error => {
        console.log(error);
    });
})

2 个答案:

答案 0 :(得分:0)

由于这两个代码段位于不同的应用程序(前端和后端)中,所以我认为没有干的办法。

答案 1 :(得分:0)

介绍具有提取逻辑的库文件

src / helper.js

exports.fetchHelper = (url) => fetch(url)
  .then(response => {
    if (response.ok) {
      return response.json();
    } else {
      res.sendStatus(response.status)
    }
  })
  .catch(console.error);

并分别使用

app.js

import { fetchHelper } from 'src/helper'; // or whatever else your bundler setup requires

searchStock = async (value) => {
  const priceURL = `/stock/${ value }/price`;
  await fetchHelper(priceURL).then((result) => {
    this.setState({
      price: result
    })
  })
}

server.js

const fetchHelper = require('src/helper').fetchHelper;

app.get('/stock/:symbol/price', (req, res) => {
  const token = 'abcde123'
  const symbol = req.params.symbol
  const apiURL = `https://sandbox.iexapis.com/stable/stock/${symbol}/price?token=T${token}`
  fetchHelper(apiURL).then((response) => {
    res.json(data);
  })

或类似的东西...