Search code examples
reactjsnode.jsaxios

(React, Node.js) AxiosError 401 occurred when sending POST request, but it worked on Postman


I wrote some code in React to perform a logout function by sending a POST request, and the below error was displayed in the browser console.

Logout error: AxiosError {message: 'Request failed with status code 401', name: 'AxiosError', code: 'ERR_BAD_REQUEST'

This is my React code:

axios.post('http://*****azure public domain*****/api/accounts/logout', {}, {
        withCredentials: true
    })
    .then(response => {
        console.log('Logout successful');
    })
    .catch(error => {
        console.error('Logout failed:', error);
    });

This is the code for CORS and cookies in my server.js.

const cors = require('cors');
app.use(cors({
    origin: (origin, callback) => {
        callback(null, true);
    },
    methods: ["POST", "GET", "PUT", "DELETE"],
    credentials: true
}));

app.use(session({
    key: 'session_cookie_name',
    secret: 'secret',
    store: sessionStore,
    resave: false,
    saveUninitialized: false,
    cookie: {
        secure: false,
        maxAge: 1000 * 60 * 60 * 24
    }
}));

Lastly this is my logout controller code.

exports.logout = async (req, res) => {
    if (req.session.username) {
        req.session.destroy(err => {
            if (err) {
                return res.status(500).json({
                    message: 'Error during logout'
                });
            }
            res.clearCookie('session_cookie_name');
            return res.status(200).json({
                message: 'Logged out successfully'
            });
        });
    } else {
        return res.status(401).json({
            message: 'Already logged out'
        });
    }
};

I think I've set the credentials correctly, but I don't know what the problem is. It worked successfully on Postman.

I tried using the axios.create method, but it returned the same error with no change.

import axios from 'axios';
const apiClient = axios.create({
    baseURL: 'http://******azure public domain******/api',
    withCredentials: true,
    headers: {
        'Content-Type': 'application/json'
    },
    timeout: 5000
});
export default apiClient;

export const logout = () => async (dispatch) => {
    try {
        const response = await apiClient.post('/accounts/logout');
        dispatch({
            type: 'LOGOUT'
        });
    } catch (err) {
        console.log('Logout error:', err);
    }
};

Solution

  • Check the request's cookie in postman and axios, are they same? This looks like the cookie issue, maybe not the same domain.