我们正在构建一个 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/