api - 在没有 Redux 的情况下难以在 REACTjs 中执行 GET 请求

标签 api http express reactjs get

我们正在构建一个 React 应用程序(没有 redux;但使用 webpack),它使用 axios 向服务器发出 GET 请求,服务器接收请求(即我们看到我们的 console.log 语句)但响应请求永远不会被服务,因为除了我们的 console.log 之外我们没有得到任何数据。服务器似乎对我们的 response.end/response.send 语句没有做任何事情。

有没有人处理过这个问题?有人有任何提示吗?请参阅下面的代码。

//Within our react component file

componentWillMount (){

      console.log("inside of componentWillMount!");

      return axios.get('/api/test')
      .then(function(resp){
        return resp.data;
        console.log('axios response: ', resp);
      })
      .catch(function(resp) {
        console.log('axios catch response ', resp);
      });
    }




//From our server.js file


    // additional middleware to set headers that we need on each request
    app.use(function(req, res, next) {

      // disable caching so we'll always get the latest activities
      res.setHeader('Cache-Control', 'no-cache');
      next();
    });

    app.get('/api/test', function(request, response, err) {
      //mongoose find all here
      console.log("We're in the server!!!");

      response.end("ennnndddd");

      if(err){
        console.log("ERROR!", err);
      }
    });




    app.listen(port, function () {
     console.log('Proxy listening on port 3000!');
    });

最佳答案

为什么要从 componentWillMount 返回调用?我不认为你应该从那个 react 生命周期事件中返回你的 axios 调用。我不认为它会被调用。

实际上,您的数据调用根本不应该在您的组件中。您应该在 action creator 中进行数据调用,然后将其分派(dispatch)给您的 reducer。

例如:

    // Action Creator
    import axios from 'axios'
    export const TEST = 'TEST'

    export function testApi (city) {
      return (dispatch) => {
        axios.get('/api/test').then(
          (resp) => {
            dispatch({
              type: TEST,
              payload: resp.data // or something like that
            })
          },
          (err) => {
            console.error(err)
          }
        )
      }
    }


    // Reducer
    import { TEST } from 'actions/index'

    export default function (state = {}, action) {
      switch (action.type) {
        case TEST:
          return Object.assign({}, state, action.payload)
      }

      return state
    }


    // Component
    componentWillMount () {
      this.props.dispatch(testApi())
    }

关于api - 在没有 Redux 的情况下难以在 REACTjs 中执行 GET 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35966433/

相关文章:

api - 我可以看到一个 Trello 用户通过 API 从 "ghost"转换为 "normal"吗?

node.js - Memcache v/s redis 用于维护持久 session ?

node.js - 安装 npm install express code UNABLE_TO_VERIFY_LEAF_SIGNATURE 时 Node js 错误无法验证第一个证书

java.lang.ClassCastException : org. apache.tomcat.dbcp.dbcp2.DelegatingPreparedStatement 无法转换为 java.sql.ResultSet

javascript - jqGrid发送编辑/删除内联信息序列化JSON格式

c 程序作为后台运行进程并且永不死机?

angular - 如何在 Angular 6 同步运行的第一个订阅中使用第二个订阅返回值?

http - 哪些 CDN 解决方案支持通过内容协商进行缓存?

http - URL 过期概念的优缺点

javascript - 类型错误 : Cannot read property '_id' of undefined in MEAN Stack