React Ajax Request 给出 CORS 错误但返回数据
Posted
技术标签:
【中文标题】React Ajax Request 给出 CORS 错误但返回数据【英文标题】:React Ajax Request gives CORS error but returns the data 【发布时间】:2018-06-07 13:58:51 【问题描述】:我正在尝试发出 GET 请求,通过 POSTMAN 可以正常工作,但在 react 上似乎不起作用。
由于某种原因,尽管出现了 CORS 错误,它也会返回数据。怎么解决?
API 负载:
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;
文件操作
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】:由于CORS,它适用于 POSTMAN 而不是在浏览器中。为了解决这个问题,您需要服务器响应数据以使“access-control-allow-origin”标头包含 * 或包含您网站的域名。
另见question
【讨论】:
是的,CORS 由浏览器强制执行,服务器只是提供建议。每个失败的 CORS 请求实际上都会发送数据。以上是关于React Ajax Request 给出 CORS 错误但返回数据的主要内容,如果未能解决你的问题,请参考以下文章
小程序从0到1网络数据请求——request合法域名|GET|POST|跨域?Ajax?