首页 > 解决方案 > 我无法在 AXIOS 中发出 GET 请求?

问题描述

为什么我收到此错误 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 req 发送请求,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();
});

截屏:

在此处输入图像描述

标签: javascriptnode.jsreactjsaxios

解决方案


我上个月遇到了这个问题,这就是我要解决的问题。试试这个后端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();
});

// 而settop 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;

推荐阅读