skip to Main Content

Request failed with status code 401
this is the error that i am getting in my react native application in response to this api call

     const fetchData = async () => {
            try {
                const response = await axios.get(`${API_URL}/general-setting`, {
                    headers: {
                        'Accept': 'application/json',
                    }
                });
                const generalSetting = response.data.data.general_setting;
                const newTheme = {
                    baseColor: `#${generalSetting.base_color}`,
                    secondColor: `#${generalSetting.secondary_color}`,
                };
                setTheme(newTheme);
            } catch (error) {
                Alert.alert('Error Fetching Theme', 'Please check your internet connection and try again.');
            }
        };

but in Postman or in the browser I am getting the response correctly. Here it is
Api response in postman

I tried the same api in browser, its working there also but not in my react native application

2

Answers


  1. In the header section there must be Authorization token for protected routes. In postman see the header section, there should be authorization token(assuming Bearer token). Copy it and in .env or .env.local paste it as

    AUTH_TOKEN=<Copied-token>
    

    and in headers along with it add

    Authorization: `Bearer ${process.env.AUTH_TOKEN}`,
    

    Note: This is just for temporary solution. For permanent solution, On time of login the cookies is set with the token value and attached with every requests to protected route.

    Login or Signup to reply.
  2. It looks like the 401 error indicates an authentication problem. Sometimes this problem can be from missing information in the request or it could be server-side, try:

    1. Authentication Headers: make sure you send the authentication token correctly in the headers, if necessary. Something like:
    headers: {
        'Authorization': `Bearer ${token}`,
        'Accept': ‘application/json’,
    }
    
    1. CORS: Although Postman and the browser work, React Native sometimes has restrictions. If it’s a CORS issue, check that the server allows requests from your app’s origin.

    As a recommendation try to check these areas and compare the headers and Authorization in Axios with Postman. Also make sure to send all the information you have in Postman (Header, Authorization, etc..).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search