0

I am trying to do a simple call to an API endpoint using the following code and keep getting the following error:

POST net::ERR_ABORTED 400 (Bad Request)

SyntaxError: Unexpected end of input

The request options

    const requestOptions = {
        method: 'POST',
        mode: 'no-cors',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            email: email,
            password: password
        })
    };

The fetch request

            await fetch("https://dev.rapptrlabs.com/Tests/scripts/user-login.php", requestOptions)
                .then(async response => await response.text())
                .then(response => response === "" ? {} : JSON.parse(response) )
                .catch(e => {
                    console.log(e)
                })

I am not sure what I am doing wrong.

Edit: I was only provided with the following documentation:

a. When the form has been successfully submitted passing all validation errors, call the following API: http://dev.rapptrlabs.com/Tests/scripts/user-login.php i. This API endpoint needs to be called with a POST request. ii. It takes two body params: email and password. iii. For testing purposes, use the following email and password: test@rapptrlabs.com / Test123. iv. A successful response will look like the following:

{ "user_id": 16, "user_email": "test@rapptrlabs.com", "user_username": "testuser", "user_is_active": 1, "user_profile_image": "http://dev.rapptrlabs.com/Tests/images/taylor_avatar.png", "user_last_active_epoch": 1544680026, "user_creation_epoch": 1544713200, "user_is_new": 1, "user_token": "6dd4737a8b7ec61313ae5e900420d46815e1d13b2902be71b97a8fbf1f421a3e" }

Edit: This issue is resolved now. The issue was that I had to use a form tag to submit the fetch request. And I have to use FormData as the request option of the fetch request.

antsmasher
  • 39
  • 4
  • Probably it's the Content-Type (i.e May not want `application/json`), but could be missing headers or a number of other things. You have not provided documentation for the endpoint you're using so it's hard to tell. – Tibrogargan Nov 15 '22 at 22:44
  • 1
    `mode: 'no-cors',` is used when you do not want to see any response at all from a cross origin request - is this a cross origin request or a same origin request? - oh, wait, you wouldn't own rapptr labs ... so, yeah, you've guaranteed there will be no response to your request – Jaromanda X Nov 15 '22 at 22:44
  • 1
    also (not the problem) - use `async`/`await` OR `.then` - and definitely not `.then(async response => await response.text())` ... that's just `.then(response => response.text())` anyway – Jaromanda X Nov 15 '22 at 22:49
  • Isn't this an error raised by the backend because the post body/content type doesn't match what it is expected? – user3252327 Nov 15 '22 at 23:13
  • 1
    @user3252327 maybe. The backend should/could respond with a 415 for using the wrong content type, but there's many backends that will just return a 400 – Tibrogargan Nov 15 '22 at 23:37
  • If the backend is in your control/code base, I would start by debugging/checking the logs in the backend rather than the frontend – user3252327 Nov 15 '22 at 23:43
  • @Jaromanda X: I wrote mode: "no-cors" because originally I was getting an error about how the fetch " has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status." – antsmasher Nov 16 '22 at 00:04
  • You need to read error messages carefully. It only says to use `mode: 'no-cors'` if an opaque response serves your needs. Your next step should have been determining if that was the case by looking up what an _"opaque response"_ means – Phil Nov 16 '22 at 00:08
  • `mode: no-cors` is NOT how you *get around CORS* - unless you don't care about the response of course - but, in this case, I think you DO care about the response ... the only way to *get around CORS* is to make the request from *your server*, not the browser – Jaromanda X Nov 16 '22 at 00:19
  • 1
    The documentation says "when the form has been successfully submitted", which could imply that the backend is literally expecting a form. (i.e. `application/x-www-form-urlencoded`) – Tibrogargan Nov 16 '22 at 00:19
  • @JaromandaX `no-cors` also affects the request by requiring / enforcing [simple headers](https://fetch.spec.whatwg.org/#simple-header). Even if OP didn't care about the response, they still can't use it to send JSON – Phil Nov 16 '22 at 00:50
  • @Phil - to be honest I didn't even look at what the OP is requesting after I saw the attempted CORS buster `no-cors` :p – Jaromanda X Nov 16 '22 at 00:59
  • @Tibrogargan Thanks. Your idea was the right answer. I had to use a form tag to submit the fetch request. And I have to use FormData as request option of the fetch request. – antsmasher Nov 16 '22 at 03:54
  • `let fd = new FormData(); fd.append("email", email"); fd.append("password", password); const requestOptions = { method: 'POST', ... body: fd }` (Shouldn't need to specify content type, but it's been a while) – Tibrogargan Nov 16 '22 at 05:24

0 Answers0