为什么我收到此错误CORS政策。我在localhost:3000
后台,后端是localhost:5000
通过向GET请求从后端服务器获取数据localhost:5000/api/users
。
userAction.js
import { FETCH_USERS } from './types';
import axios from 'axios';
export const fetchUsers = () => dispatch => {
axios.get(`localhost:5000/api/users`)
.then( users =>
dispatch({
type: FETCH_USERS,
payload: users
})
)
.catch( error => {
console.log(error);
});
};
userReducer.js:
import { FETCH_USERS } from '../actions/types';
const initialState = {
items: []
}
export default function (state = initialState, action) {
switch (action.type) {
case FETCH_USERS:
return {
...state,
items: action.payload
};
default:
return state;
}
}
现在,我正在获取GET请求,localhost:5000/api/users
并且我在客户端localhost:3000
上添加了以下代码,server.js
但仍显示相同的错误。
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
屏幕截图:
我上个月遇到了这个问题,这是我要解决的问题。对于后端accpet跨域,请尝试以下操作(我的后端是nodejs):
app.use(function(req, res, next) {
//to allow cross domain requests to send cookie information.
res.header('Access-Control-Allow-Credentials', true);
// origin can not be '*' when crendentials are enabled. so need to set it to the request origin
res.header('Access-Control-Allow-Origin', req.headers.origin);
// list of methods that are supported by the server
res.header('Access-Control-Allow-Methods','OPTIONS,GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept, X-XSRF-TOKEN');
next();
});
//机顶盒axios默认是这样的。我为客户端使用React
import axios from 'axios';
const instance = axios.create({
baseURL: 'http://localhost:5000/',
withCredentials: true,
});
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-
urlencoded';
axios.defaults.withCredentials = true;
axios.defaults.crossDomain = true;
export default instance;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句