【问题标题】:Reactjs recieves error even when backend is showing 200 OK即使后端显示 200 OK,Reactjs 也会收到错误
【发布时间】:2018-08-19 07:16:59
【问题描述】:

当我从我的 ReactJS 前端发送 GET 请求时,即使我的 django 后端在终端中显示 [10/Mar/2018 23:31:08] "GET /post/ HTTP/1.1" 200 930,它也会收到错误。

我正在使用 redux sagas。

src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import { BrowserRouter, Route, Switch, Redirect } from 'react-router-dom';
import createSagaMiddleware from 'redux-saga'
import rootSaga from './sagas'
import rootReducer from './reducers';
import PostsIndex from './components';

const sagaMiddleware = createSagaMiddleware();
const store = createStore(
  rootReducer,
  applyMiddleware(sagaMiddleware)
);
sagaMiddleware.run(rootSaga);

ReactDOM.render(
  <Provider store={store}>
    <BrowserRouter>
      <div>
        <Switch>
          <Route path="/" component={PostsIndex}/>
        </Switch>
      </div>
    </BrowserRouter>
  </Provider>
  , document.querySelector('.container'));

src/components/index.js

import React, { Component } from 'react';
import { fetchPosts } from '../actions';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import _ from 'lodash';


class PostsIndex extends Component {
  componentDidMount() {
    this.props.fetchPosts();
  }

  renderPosts() {
    return _.map(this.props.posts, (post) => {
      return(
        <li className="list-group-item" key={post.id}>
          {post.text}
        </li>
      )
    })
  }

  render() {
    const { posts } = this.props
    if (posts.isLoading) {
      return (
          <div>
            <h3>Loading...</h3>
          </div>
      )
    } else if (posts.error) {
      return (
        <div>
          <h3>Error getting posts</h3>
          <h2>{JSON.stringify(posts.error)}</h2>
        </div>
      )
    } else {
      return (
        <div>
          <div className="text-xs-right">
            <Link className="btn btn-primary" to="/posts/new">
              Add a Post
            </Link>
          </div>
          <h3>Posts</h3>
          <ul className="list-group">
            {this.renderPosts()}
          </ul>
        </div>
      );
    }
  }
}

function mapStateToProps({ posts }){
  return { posts }
}

export default connect(mapStateToProps, { fetchPosts })(PostsIndex);

src/actions/index.js

export const FETCH_POSTS = 'fetch_posts';

export function fetchPosts() {
  return { type: FETCH_POSTS };
}

src/api/index.js

import axios from 'axios';
const ROOT_URL = 'http://127.0.0.1:8000';

export function fetch(endpoint) {
  return axios.get(`${ROOT_URL}/${endpoint}/`)
            .then(response => ({ response }))
            .catch(error => ({ error }));
}

src/reducers/index.js

import { combineReducers } from 'redux';
import { POSTS_REQUESTED, POSTS_RECEIVED, POSTS_REQUEST_FAILED } from '../sagas';
import _ from 'lodash';

function postsReducer(state = {}, action) {
  switch(action.type) {
    case POSTS_REQUESTED:
        return {
            content: null,
            isLoading: true,
            error: null
        }
    case POSTS_RECEIVED:
      return {
          content: _.mapKeys(action.posts, 'id'),
          isLoading: false,
          error: null
      }
    case POSTS_REQUEST_FAILED:
      return {
          content: null,
          isLoading: false,
          error: action.error
      }
    default:
      return state;
  }
}

const rootReducer = combineReducers({
  posts: postsReducer,
});

export default rootReducer;

src/sagas/index.js

import { call, put, takeEvery } from 'redux-saga/effects'
import { fetch } from '../api';
import { FETCH_POSTS } from '../actions';

export const POSTS_REQUESTED = 'posts_requested';
export const POSTS_RECEIVED = 'posts_recieved';
export const POSTS_REQUEST_FAILED = 'posts_request_failed';

export function* fetchPosts() {
  yield put({ type: POSTS_REQUESTED })
  const { response, error} = yield call(fetch, 'post');
  if (response)
    yield put({ type: POSTS_RECEIVED, posts: response })
  else
    yield put({ type: POSTS_REQUEST_FAILED, error })
}

export function* watchFetchPosts() {
  yield takeEvery(FETCH_POSTS, fetchPosts);
}

// single entry point to start all Sagas at once
export default function* rootSaga() {
  yield [
    watchFetchPosts()
  ]
}

我得到的输出是

获取帖子时出错 {"config":{"transformRequest":{},"transformResponse":{},"timeout":0,"xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength ":-1,"headers":{"接受":"application/json, 文本/纯文本, /"},"method":"get","url":"http://127.0.0.1:8000/post/"},"request":{}}

当我将该网址复制粘贴到我的浏览器中时,它可以完美运行,所以它一定是前端的问题。

为什么会出现这个错误?

【问题讨论】:

  • 我认为在错误上使用 JSON.stringify 可能会删除一些有用的信息。当您阅读 post.error.message 时,您会得到什么? (这也可能有用:github.com/axios/axios#handling-errors
  • @MartinKadlec 当我这样做时,它显示网络错误
  • @MartinKadlec,我也查看了该文档。 error 没有响应成员,请求成员为空,所以没有什么帮助。
  • 网络标签是怎么说的?
  • @bigless 它显示 /post/ 请求并显示 200。其中还有其他四件事我不确定是否相关。 GET http://localhost:3000/ 返回 304、GET http://localhost:3000/static/js/bundle.js 返回 304、GET http://localhost:3000/sockjs-node/info?t=1520736729536 返回 200 和 GET http://localhost:3000/sockjs-node/425/ljoxvei4/websocket 返回 101

标签: javascript reactjs redux redux-saga


【解决方案1】:

原来问题与this有关

因为我使用的是 django-rest,所以我只需要像 this answer 一样将 django-core-headers 添加到我的后端

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-18
    • 2016-12-15
    • 2013-06-28
    • 1970-01-01
    • 2013-08-04
    • 1970-01-01
    • 2012-04-09
    • 2010-11-24
    相关资源
    最近更新 更多