jQuery ajaxSetup with ES6

2019-08-02 21:32发布

问题:

How do I replicate the behavior of jQuery's ajaxSetup with vanilla JS (ES6 in this case)?

Here's what I'm trying to achieve. Currently I have in my app.js:

$(document).ready(()=>{
    $.ajaxSetup({
        data: {'_token': $('meta[name="csrf-token"]').attr('content')}
    });     
 })

So when I perform any ajax request in any other file, _token will be include to the data json object that I'm providing, that way I don't have to specify _token on every call making sure that it's never missed.

How to do this with ES6 only?

回答1:

Wrap the Fetch api and store your base data and merge that with whatever you send with it.

class MyFetch {
  constructor(data) {
    this.data = data
  }

  post(url, data) {
    let requestData = {
      ...this.data,
      ...data
    }
    return fetch(url, {
      method: 'POST',
      body: JSON.stringify(requestData)
    })
  }
}

let myFetch = new MyFetch({
  _token: 'helloworld'
})

myFetch.post('https://httpbin.org/post',{moreData:'more'})
  .then((res) => res.json())
  .then(json => {
    console.log('Data sent:', json.data)
  })