admin管理员组

文章数量:1303428

Why I am getting this error CORS policy. I am on localhost:3000 and backend is at localhost:5000 I am getting data from backend server by making GET request to 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;
    }
}

Now I am making GET req to localhost:5000/api/users and I am on client localhost:3000 I have added following code in server.js but still showing the same error.

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();
});

Screenshot:

Why I am getting this error CORS policy. I am on localhost:3000 and backend is at localhost:5000 I am getting data from backend server by making GET request to 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;
    }
}

Now I am making GET req to localhost:5000/api/users and I am on client localhost:3000 I have added following code in server.js but still showing the same error.

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();
});

Screenshot:

Share edited Nov 2, 2018 at 6:11 Farhan Yaseen 2,7072 gold badges24 silver badges39 bronze badges asked Nov 2, 2018 at 5:52 fun jokerfun joker 1,7277 gold badges34 silver badges54 bronze badges 1
  • If you are using express then I would remend you using cors middleware github./expressjs/cors – Juned Lanja Commented Nov 2, 2018 at 6:13
Add a ment  | 

5 Answers 5

Reset to default 4

I met this problem last month, here is what i did to resolve. Try this for backend accpet cross domain (my backend is 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();
});

// And settop axios default like this. I use React for client

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;

In your "package.json" you can add a proxy to the server. Just one line:

"proxy": "http://localhost:5000/"

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "axios": "^0.18.0",
    "react": "^16.4.2",
    "react-dom": "^16.4.2",
    "react-router": "^4.3.1",
    "react-router-dom": "^4.3.1",
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },
  "proxy": "http://localhost:5000/"
}

You can easily connect frontend (react) with backend(node-express) and solve CORS issues by adding proxy like so:

Inside package.json add the proxy property with the backend url:

proxy": "http://localhost:5000/"

If you are using express server then use cors middleware. It's easy to use and manage CROS requests using this middleware.

Node.js CORS middleware

You have to enable cors in your project.

Try this:

  1. npm install cors --save
  2. In your server.js

    const cors =require('cors')
    const express = require('express')
    const app = express()
    app.use(cors()) // app is your express object
    

本文标签: javascriptI am not able to make a GET request in AXIOSStack Overflow