vue.js的ajax方法(不用jquery)如何加headers??官方例子没有headers...
写的还是不错的,赞一个,我想获得你的经验和程序,谢谢大家支持
vue.js本身没有ajax方法。
你用的是某个第三方的ajax库吧,去看看这个ajax库的api说明文档。
如果api说明文档中没有headers的说明,可能这个ajax库本就不支持设置headers。
你可以换别的ajax库,或者直接用原生XMLHttpRequest。
http://www.runoob.com/vue2/vuejs-ajax.html
下面是对axios的一个 封装,在请求拦截中设置headders
import Axios from 'axios'
import Cookies from 'js-cookie'
import { Message } from 'iview'
import router from '@/router'
class httpRequest {
constructor () {
this.options = {
method: '',
url: '',
type: 'json'
}
// 存储请求队列
this.queue = {}
}
// 销毁请求实例
destroy (url) {
delete this.queue[url]
const queue = Object.keys(this.queue)
return queue.length
}
// 请求拦截
interceptors (instance, url) {
// 添加请求拦截器
instance.interceptors.request.use(config => {
// 添加token
const token = Cookies.get('token')
if (token) {
config.headers['Authorization'] = Cookies.get('token')
}
// Spin.show()
// 在发送请求之前做些什么
return config
}, error => {
// 对请求错误做些什么
return Promise.reject(error)
})
// 添加响应拦截器
instance.interceptors.response.use((res) => {
let { data } = res
const is = this.destroy(url)
if (!is) {
setTimeout(() => {
// Spin.hide()
}, 500)
}
if (data.code === -6) {
Message.error(data.msg)
router.push({name: 'login', params: {path: location.pathname.substring(1)}})
}
return data
}, (error) => {
Message.error('服务内部错误')
// 对响应错误做点什么
return Promise.reject(error)
})
}
// 创建实例
create () {
let conf = {
// baseURL: 'http://localhost:8085/',
baseURL: 'https://blog.yuanmen.top/',
timeout: 20000,
headers: {
'Content-Type': 'application/json; charset=utf-8',
'X-URL-PATH': location.pathname
}
}
return Axios.create(conf)
}
// 合并请求实例
mergeReqest (instances = []) {
//
}
// 请求实例
request (options) {
var instance = this.create()
this.interceptors(instance, options.url)
options = Object.assign({}, options)
this.queue[options.url] = instance
return instance(options)
}
}
export default httpRequest
推荐一个vue官方的ajax封装的库
API请求利器啊
https://www.kancloud.cn/yunye/axios/234845
https://www.jianshu.com/p/7a9fbcbb1114
另推荐一个模版 element
http://element-cn.eleme.io/#/zh-CN/component/installation
vue本身是没有ajax的,库什么的楼上都说了,不过你要设计请求头的时候要保证这个头被支持
举个例子 axios的全局追加
axios.interceptors.request.use(
config => {
// 发送请求拦截
config.headers.token = 12313`
// console.log(config)
return config
},
error => {
return Promise.reject(error)
}
)