如何使用vanilla JS(在本例中为ES6)复制jQuery的ajaxSetup的行为?
这是我想要实现的目标。目前我的app.js中有:
$(document).ready(()=>{
$.ajaxSetup({
data: {'_token': $('meta[name="csrf-token"]').attr('content')}
});
})
因此,当我在任何其他文件中执行任何ajax请求时,_token将包含在我提供的数据json对象中,这样我就不必在每次调用时指定_token,以确保它永远不会错过。
如何仅使用ES6执行此操作?
答案 0 :(得分:1)
包装Fetch api并存储您的基础数据并将其与您发送的任何内容合并。
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)
})