Fetch post api di react hasilnya nan

pas di console.log ada hasilnya

{title: "123", description: "123", check: "on"}

handleSubmit = (e) => {
        e.preventDefault()
        let data = {
            title: this.state.title,
            description: this.state.description,
            check: this.state.check
        }
        fetch("http://localhost:5000/api/sick", {
            method: 'POST',
            headers: {
                "Authorization" : localStorage.getItem('token')
            },
            body: JSON.stringify(data)
        })
        console.log(data)
    }

dan di servernya saya console.log isi req.bodynya hasilnya NaN

const title = req.body.title
    const description = req.body.description
    const file = "tes"
    const check = req.body.check
    console.log(title + description + check)

avatar tonisuwendi
@tonisuwendi

169 Kontribusi 36 Poin

Dipost 4 tahun yang lalu

Tanggapan

saya coba console.log satu persatu hasilnya undefined, kenapa yah?

1 Jawaban:

Jawaban Terpilih

solved

menambahkan 'Content-Type': 'application/json' di headers, sehingga kodenya menjadi seperti ini

<pre> handleSubmit = (e) =&gt; { e.preventDefault() let data = { title: this.state.title, description: this.state.description, check: this.state.check } fetch("http://localhost:5000/api/sick", { method: 'POST', headers: { "Authorization" : localStorage.getItem('token'), 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) console.log(data) } </pre>

avatar tonisuwendi
@tonisuwendi

169 Kontribusi 36 Poin

Dipost 4 tahun yang lalu

Login untuk ikut Jawaban