5

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.

2
  • 4
    As the name indicates, the OAuth2PasswordRequest_Form_ requires you to send your form variables as regular form data - not as JSON. You can use FormData() to make fetch serialize the data as a form data post instead Commented May 17, 2022 at 18:53
  • Thank you very much. That did the trick along with switching to axios. Commented May 17, 2022 at 19:16

2 Answers 2

2

We can use FormData to send form data using fetch. If we don't pass any content type header then it uses 'multipart/form-data'

const loginForm = document.querySelector(".login-form")

loginForm.addEventListener("submit", (e) => {
  e.preventDefault()

  const formData = new FormData(loginForm)

  fetch("http://localhost:8000/auth/token", {
    method: "POST",
    body: formData,
  })
  .then((res) => res.json())
  .then((token) => {
    console.log("Token", token)
    // window.location.href = "/"
  })
  .catch((err) => {
    console.log("Error", err)
  })
})

Other way is to use URLSearchParams with FormData and set content-type to 'application/x-www-form-urlencoded'

const formData = new URLSearchParams(new FormData(loginForm))

fetch("http://localhost:8000/auth/token", {
  method: "POST",
  body: formData,
  headers: {
    "Content-Type": "application/x-www-form-urlencoded"
  }
})
Sign up to request clarification or add additional context in comments.

Comments

0

For me, this solve problem:

https://axios-http.com/docs/urlencoded

Problem actualy in headers. FastAPI wait for "application/x-www-form-urlencoded" and in js (axios for example) we can encode body like this:

const params = new URLSearchParams();

params.append('param1', 'value1');
params.append('param2', 'value2');

axios.post('/api/.../get_token', params);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.