Home > OS >  Post form-data on Axios (React)
Post form-data on Axios (React)

Time:09-02

I've got the following component in React:

    const login = async (username, password) => {
    const response = await axios.post('/auth/jwt/login', {
        username,
        password
    });
    const {accessToken, user} = response.data;

    setSession(accessToken);

    dispatch({
        type: 'LOGIN',
        payload: {
            user,
        },
    });
};

Now, the problem is my API is expecting a form, whereas this request is sending a json on the body, thus I'm getting a 422 error (unprocessable entity).

I've tried creating a FormData() object but no luck so far:

    const formData = new FormData();

    const login = async () => {
    const response = await axios.post('/auth/jwt/login', {
        username: formData.username,
        password: formData.password
    });
    const {accessToken, user} = response.data;

    setSession(accessToken);

    dispatch({
        type: 'LOGIN',
        payload: {
            user,
        },
    });
};

Can anyone please help me? Thanks!

CodePudding user response:

Specifically you want to POST the data as application/x-www-form-urlencoded instead of as a JSON-encoded body. According to the documentation, in the browser you would use URLSearchParams for this. For example:

const params = new URLSearchParams();
params.append('username', username);
params.append('password', password);
const response = await axios.post('/auth/jwt/login', params);

(That same documentation provides other options as well, to include 3rd party libraries or to POST from NodeJS. The above is specific to in-browser code with no 3rd party libraries.)

CodePudding user response:

The previous solution didn't work for me. This did:

    const form = new FormData();
    form.append('username', username)
    form.append('password', password)
    const response = await axios.post('/auth/jwt/login', form,
        { headers: { 'Content-Type': 'multipart/form-data' } }
    );

In fact I could just do this:

    const login = async (username, password) => {
    const response = await axios.post('/auth/jwt/login', {
        username,
        password
        },
        { headers: { 'Content-Type': 'multipart/form-data' } }
    );
    const {accessToken, user} = response.data;

    setSession(accessToken);

    dispatch({
        type: 'LOGIN',
        payload: {
            user,
        },
    });
};
  • Related