Saifur Rehman
Saifur Rehman

Reputation: 65

CORS error: Request header field authentication is not allowed by Access-Control-Allow-Headers in preflight response

While loging out, this error occur. Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/auth/logout/' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field authentication is not allowed by Access-Control-Allow-Headers in preflight response.

I'm calling logout function of auth.js in as onClick. I don't know why I get logout when I refresh my page.

reducer.js

 case LOGOUT_SUCCESS:
      localStorage.removeItem("token");
      return {
        ...state,
        isAuthenticated: null,
        isLoading: false,
        user: null,
        isFreelancer: false
      };

logout function of action/auth.js

export const logout = () => (dispatch, getState) => {
  const token = getState().auth.token;

  const config = {
    headers: {
      "Content-Type": "application/json"
    }
  };

  if (token) {
    config.headers["Authentication"] = `Token ${token}`;
  }

  axios
    .post("http://127.0.0.1:8000/api/auth/logout/", null, config)
    .then(res => {
      dispatch({ type: LOGOUT_SUCCESS });
    })
    .catch(err => {
      console.log(err.message);
    });
};

I expect to log out immediately but I get logged out while I refresh my page everytime.

Upvotes: 0

Views: 1037

Answers (1)

balmukund kumar
balmukund kumar

Reputation: 149

If you are using Create-React-App, you can simply do this in your package.json file:

"proxy": "http://127.0.0.1:8000",

It will be proxy request and browser will not block response.

Upvotes: 1

Related Questions