1

I'm making a fetch request from react-native. Why will A send the body data correctly, but B come back as undefined?

    let usrn = 'ususus'
    lew pwrd = 'pwpwpw'

    let bodyData = {
        'u': usrn,
        'p': pwrd,
    }

Specifically the body data with JSON.stringify()?

=> A
    return fetch(url, {
            method: "POST",
            headers: headers,
            body: JSON.stringify({
                'u': usrn,    // <= can return this value on server
                'p': pwrd,    // <= can return this value on server
            })
        })

=> B
    return fetch(url, {
            method: "POST",
            headers: headers,
            body: JSON.stringify({ bodyData }) // <= returns undefined on server
        })

2 Answers 2

10

bodyData is an object, you don't need to wrap it with curly brackets again:

body: JSON.stringify(bodyData);
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, I thought this was it but I could get it to work.
when I saw the question, my mind starts to think about the us undefined xD but, yeah you're right
There is two problems in your second approach, the {} and also what @Kenry mentioned. So you will have to fix that as well
Thanks to both of you typo fixed.
2

variable us is not defined..

let bodyData = {
    'u': us,
    'p': pwrd,
}

In the code:

return fetch(url, {
        method: "POST",
        headers: headers,
        body: JSON.stringify({
            'u': usrn,    // <= can return this value on server
            'p': pwrd,    // <= can return this value on server
        })
    })

you are using the property 'u' the variable usrn. it is defined

Change bodyData to..

let bodyData = {
'u': usrn,
'p': pwrd,

}

1 Comment

body: JSON.stringify(bodyData);. Yes, but this is the right answer. the guy has right

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.