fun joker
fun joker

Reputation: 1727

I am not able to make a GET request in AXIOS?

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:

enter image description here

Upvotes: 2

Views: 6889

Answers (5)

Theo Itzaris
Theo Itzaris

Reputation: 4681

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/"

Upvotes: 1

Ankit Manchanda
Ankit Manchanda

Reputation: 582

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
    

Upvotes: 0

hypnagogia
hypnagogia

Reputation: 173

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/"
}

Upvotes: 2

Juned Lanja
Juned Lanja

Reputation: 1484

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

Upvotes: 0

Truong Dang
Truong Dang

Reputation: 3427

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;

Upvotes: 4

Related Questions