Fetch Error: Failed to execute ‘fetch’ on ‘Window’: Request with GET/HEAD method cannot have body

Error code: src/api/index.js

import Fetch from'../fetch/index' 
import jk from './ jk ' 
export default {
  verifycodeApi: params => Fetch(jk.verifycode, {method:'get' ,body: params})
}

In the get method here, the body is used to accept the parameters, so an error is reported.

 

solution:

In the packaged fetch.js

const Fetch = (url, option = ()) => {
   // Format the data of the get request (the get request of fetch needs to splice the parameters behind the url) 
  if (option.method ==='get') {
    if (option.data) {
      url = url + formatUrl(option.data)
    }
  }

  // Process non-get request headers and request bodies 
  if (option.method ==='post' || option.method ==='put' || option.method ==='delete' ) {
    option.headers[ 'Content-Type'] = option.headers['Content-Type'] ||'application/json' 
    option.body = qs.stringify(option.body)
     // option.body = JSON.stringify( option.body) 
  }

  delete option.data 
}

The key point is the code marked in orange. This is to create a data attribute for the get method. After the url is spliced, delete the data attribute with delete.

 

So, in src/api/index.js

// The api file stores the interface folder 
import Fetch from'../fetch/index' 
import jk from './ jk ' 
export default {
  manageloginApi: params => Fetch(jk.managelogin, {method:'post' , body: params}),
  verifycodeApi: params => Fetch(jk.verifycode, {method:'get' , data: params})
}

You can use the data attribute to store the parameters passed by get, avoiding the error of body passing parameters

Read More:

Leave a Reply

Your email address will not be published. Required fields are marked *