React Ajax Request提供CORS错误但返回数据

时间:2017-12-26 20:33:27

标签: javascript reactjs redux react-redux redux-thunk

我正在尝试发出一个GET请求,这可以通过POSTMAN正常工作,但是反应似乎不起作用。

出于某种原因,尽管存在CORS错误,它也会返回数据。如何解决?

API负载: enter image description here

index.js(Redux设置)

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router } from 'react-router-dom';
import App from './App';

import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import ReduxPromise from 'redux-promise';
import thunk from 'redux-thunk';

import createHistory from 'history/createBrowserHistory'
import { ConnectedRouter, routerReducer, routerMiddleware, push } from 'react-router-redux'

import {assumeRole} from './libs/awsLib';

import './index.css';

import reducers from './reducers';
import {LOGIN, LOGOUT} from "./actions/UsersActions";
import {api} from "./actions/api";

const history = createHistory();
const myRouterMiddleware = routerMiddleware(history);

const createStoreWithMiddleware = applyMiddleware(ReduxPromise, thunk, myRouterMiddleware)(createStore);

ReactDOM.render(
  <Provider store={createStoreWithMiddleware(reducers)}>
    <ConnectedRouter history={history}>
      <App />
    </ConnectedRouter>
  </Provider>,
  document.getElementById('root')
);

FileListReducer

import {GET_DOCUMENTS} from "../actions/index";

export default function(state = [], action) {
    //reducers should return a new object, never mutate the current state

    switch (action.type) {
        case GET_DOCUMENTS:
            return action.payload;
    }

    return state;
}

FilesActions

import 'whatwg-fetch'
import {api} from './api';
import config from '../config.js';

export const GET_DOCUMENTS = 'GET_DOCUMENTS';

export function getDocuments() {
    return (dispatch) => {
        const request = api.fetch('warpig/document/?userId='+localStorage.getItem("id")).then((res) => {
            dispatch({
                type: GET_DOCUMENTS,
                payload: {data: res, success: res.status == 200}
            })
        }, (err, data) =>  {
            console.log(err, data);
        });
    }
}

我的方式来调用getDocuments()

...

    componentDidMount() {
        this.getDocuments();
    }

    getPrograms() {
        this.props.fetchPrograms();
    }
...

function mapDispatchToProps(dispatch) {
    return bindActionCreators({ fetchPrograms, uploads3, login, assignToken, getDocuments }, dispatch);
}

function mapStateToProps({ programs, fileUpload, auth, filesList }) {
    return { programs, fileUpload, auth, filesList };
}

export default connect(mapStateToProps, mapDispatchToProps)(FileUpload)

主要问题是通过POSTMAN工作,但是当我通过React在我的浏览器上发出HTTP GET请求时,尽管它返回了数据,但是,它可能是什么?

1 个答案:

答案 0 :(得分:2)

由于CORS,它适用于POSTMAN而非浏览器。为了解决这个问题,您需要服务器响应数据以获得&#34; access-control-allow-origin&#34;标头包含*或包含您网站的域名。

另见question