简体   繁体   中英

jQuery ajaxSetup with ES6

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?

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) })

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