-1

I have a POST request to a FastAPI project which works fine in postman and swagger UI for the same request.

enter image description here

When I try to use the fetch/axios method in React native for the same request, I get 422 Unprocessable Entity error.

const onLoginPressed = async () => {
    const headers = {
      'Content-Type': 'application/text',
      'Access-Control-Allow-Origin': '*',
      "Access-Control-Allow-Headers": "Content-Type",
      'Access-Control-Allow-Methods': 'POST,PATCH,OPTIONS',
    }
    const response = await fetch("http://127.0.0.1:8000/***/v1/***/***-token", {
        'method': "POST",
        'mode': 'no-cors',
        'withCredentials': true,
        'headers': headers,
        'body': JSON.stringify({
          username: '***@**.com',
          password: '****',
        }),
      })
    const json = await response.json();
    console.log(json);
}

enter image description here

I tried POST method to send login data and expected to get an access token / secret key. Expected output

enter image description here

I am not sure why this is not working in React native code. I initially saw recommendations to put await in front of the fetch since the call is async but this did not fix the errors(see the above code).

I have the following CORS in the backend:

# BACKEND_CORS_ORIGINS is a JSON-formatted list of origins
    # e.g: '["http://localhost", "http://localhost:4200", "http://localhost:3000", \
    # "http://localhost:8080", "http://local.dockertoolbox.tiangolo.com"]'
    BACKEND_CORS_ORIGINS: List[AnyHttpUrl] = []

# Set all CORS enabled origins
if settings.BACKEND_CORS_ORIGINS:
    app.add_middleware(
        CORSMiddleware,
        allow_origins=[str(origin) for origin in settings.BACKEND_CORS_ORIGINS],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

What am I missing?

Liton
  • 1,398
  • 2
  • 14
  • 27
  • In addition to the link provided above, please have a look at [this answer](https://stackoverflow.com/a/73963905/17865804) and [this answer](https://stackoverflow.com/a/75041731/17865804). You might find [this](https://stackoverflow.com/a/73662576/17865804) and [this](https://stackoverflow.com/a/75188418/17865804) helpful as well. – Chris Jun 25 '23 at 10:41

1 Answers1

1

API expects form data, so building a request goes something like this

let formData = new FormData()
formData.append('username', '***@**.com')
formData.append('password', '****')

const response = await fetch('http://127.0.0.1:8000/***/v1/***/***-token', {
   method: 'POST',
   body: formData
})
user18309290
  • 5,777
  • 2
  • 4
  • 22