Cant figure out how to make put request using fetch in javascript

I made a post request and my site deploy is in uploading state. Now I need to make a PUT request to upload file. I read the article about deploying sites using postman. When I make PUT request using postman it works. But I am trying to do it using javascript.

What should be content-type and body If I want to upload file?

Something like:

import fs from 'fs'
import {sha1FileSync} from 'sha1-file'
const authorization = 'Bearer {token}' // auth token here
const files : Array<string> = [] // array of file paths relative to current directory
// the following function generates a SHA1 of all files, uses this package: https://www.npmjs.com/package/sha1-file (untested)
Promise.all<Array<string>>(files.map(file => {
  return sha1FileSync(file)
})).then(shaFiles => {
  // sends the file object as a JSON to Netlify
  fetch('https://api.netlify.com/api/v1/sites/{site_id}/deploys', {
    body: JSON.stringify(files.reduce((previousValue, currentValue, currentIndex) => {
      return previousValue[currentValue] = shaFiles[currentIndex]
    }, <{
      [key : string] : string
    }>{})),
    headers: {
      authorization
    },
    method: 'post'
  }).then(createdDeployResponse => {
    return createdDeployResponse.json()
    // no error checking done - highly risky
  }).then(createdDeploy => {
    Promise.all(files.map(file => {
      // no error checking again
      return fetch(`https://api.netlify.com/api/v1/deploys/${createdDeploy.id}/files/index.html`, {
        body: fs.readFileSync(file),
        headers: {
          authorization,
          'content-type': 'application/octet-stream'
        },
        method: 'put'
      }).then(response => {
        return response.json()
      }).then(deploy => {
        return deploy
      })
    })).then(() => {
      console.log('deploy should be done here')
    })
  })
})

This is in TypeScript and not tested, but should give you an idea.

1 Like