posva / mande

<700 bytes convenient and modern wrapper around fetch with smart extensible defaults
https://mande.esm.is
MIT License
1.19k stars 42 forks source link

how can i post a formdata request? #388

Closed liuxia19872003 closed 1 year ago

liuxia19872003 commented 1 year ago

i want to request a token from a fastapi backend,and the code below is ok.

fetch(
        loginBaseUrl,
        {
            method: 'post',
            body: 'username=admin&password=123',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        }
    )

how can i do it with mande? the code below cann't work.

const login =mande(loginBaseUrl)
const data =  login.post(
'',
 'username=admin&password=123',
{
 headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
}
)
console.log(data)
posva commented 1 year ago

You pass the Formdata instance and set the content-type to undefined

liuxia19872003 commented 1 year ago

I read the mande's code and think that coding like this will be more elegant:

export async function mandeLoginGetToken(username: string, password: string) {
  console.log("mandeLoginGetToken-1");

  const params = new URLSearchParams();
  params.append("username", username);
  params.append("password", password);

  const tokenapi = mande(`${mandeBaseUrl}/login/access-token`);
  const res = await tokenapi.post<IToken>(null, {
    body: params.toString(),
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
    },
  });
  return res;
}