'How to pass data from client to fastapi OAuth2PasswordRequestForm via a post request?

I am using nextjs for my frontend and fastapi for my backend. When I run this code in the frontend:

async function test() {
    const response = await fetch("http://127.0.0.1:8000/token", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({
            username: "johndoe",
            password: "secret",
        }),
    }).then((res) => res.json());
    return {
        props: { data: response },
    };
}

useEffect(() => {
    const data = test();
    console.log(data);
}, []);

I get a fulfilled promise which is an array of length two where each entry is:

loc: (2) ['body', 'username']
msg: "field required"
type: "value_error.missing"

and this error message: "POST http://127.0.0.1:8000/token 422 (Unprocessable Entity)" in the console.

My backend can be found here https://github.com/ColeBlender/oauth2-test. I have been trying to figure this out for days and can't find an answer so any help is greatly appreciated.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source