简体   繁体   中英

Sending file and data with Fetch

I have an application in react. The state of my application is as follows

const [book, setBook] = useState({
    title: '',
    cover: {}
    numberPages: 0,
    resume: '',
    date: date,
});

Cover prop contains a file. When I try to convert the state to json (JSON.stringify(book)) to send it with FETCH, the cover property is an empty object. How can I send this information correctly?

My on submit event form

 let handleForm = (e) => {

    data = JSON.stringify(book);

    let info = {
        method: 'POST',
        body: data,
        headers: { 
            'X-CSRF-TOKEN': header,
            "Content-Type": "application/json",
            "Accept": "application/json, text-plain, */*"
         }
    }

    fetch('/books/add', info)
        .then(response => response.json())
        .then(result => console.log(result))
        .catch(error => console.log(error));

    e.preventDefault();
}

when you are sending files in fetch make sure u use the formdata

var data = new FormData()
data.append('title', book.title)
data.append('cover', book.cover)

fetch('/', {
  method: 'POST',
  body: data
})

Hope it works. If not please comment your code where you are making api call

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM