Vue2使用拦截不了请求
今天用到,按理它应该会拦截所有的AJAX请求,但是运行起来没拦截,记录一下:
1.安装
2.创建/src/
const Mock = require("mockjs")
let Result = {
code:200,
msg:'成功',
data:null
}
Mock.mock('/api/getVerifyCode','get',()=>{
console.log("mock执行getVerifyCode")
return Result;
})
添加:
require("./mock")
随便在页面上做了个按钮,按钮会触发点击事件发送请求(这里我用了axios发请求):
//点击事件
getVerifyCode(){
console.log("获取验证码")
this.$axios.get(
'/api/getVerifyCode',
).then(response => {
console.log(response)
})
.catch(error => {
console.log(error)
})
}
这个事件就是向/api/getVerifyCode发生get请求,但浏览器报错:
OPTIONS http://localhost:8080/api/getVerifyCode net::ERR_CONNECTION_REFUSED
Error: Network Error
at createError (?2d83:16)
at [as onerror] (?b50d:117)
at (?96eb:8476)
at (?96eb:8304)
发不了请求,看了下地址,是向8080端口发请求的,想起我之前把vue的启动端口改了8081,并且在项目里/src/的文件加了这句:
axios.defaults.baseURL = "http://localhost:8080"
因为后端那边的端口用的8080所以加了这句,但是现在又不向后端发请求,那就把这句删了试试,删了之后能正常拦截请求了,果然是这里的问题。