相关代码
- SpringBoot跨域请求 解决方案汇总
- vue3 中 vue.config.js 修改端口 添加代理配置
@RestController
@RequestMapping("/user")
public class UserController {
@PostMapping("/login1")
public void login1(String username, String password) {
System.out.println(username + " " + password);
}
@PostMapping("/login2")
public void login2(@RequestParam String username, @RequestParam String password) {
System.out.println(username + " " + password);
}
@PostMapping("/login3")
public void login3(User user) {
System.out.println(user);
}
@PostMapping("/login4")
public void login4(@RequestBody User user) {
System.out.println(user);
}
}
工具类
import axios from 'axios'
import {ElMessage} from 'element-plus'
import store from '@/store'
import router from '@/router'
const http = axios.create({
baseURL: '/',
timeout: 10000,
withCredentials: true,
})
// 拦截请求
http.interceptors.request.use(
config => {
const { authorization } = store.state.app
if (authorization) {
config.headers.Authorization = `Bearer ${authorization.token}`
}
return config
},
error => {
// console.log(error);
return Promise.reject(error)
}
)
// 拦截响应
http.interceptors.response.use(
// 响应成功进入第1个函数,该函数的参数是响应对象
response => {
return response.data
},
// 响应失败进入第2个函数,该函数的参数是错误对象
async error => {
// 如果响应码是 401 ,则请求获取新的 token
// 响应拦截器中的 error 就是那个响应的错误对象
if (error.response && error.response.status === 401) {
// 校验是否有 refresh_token
const { authorization } = store.state.app
if (!authorization || !authorization.refresh_token) {
if (router.currentRoute.value.name === 'login') {
return Promise.reject(error)
}
const redirect = encodeURIComponent(window.location.href)
router.push(`/user/login?redirect=${redirect}`)
// 清除token
store.dispatch('app/clearToken')
setTimeout(() => {
ElMessage.closeAll()
try {
ElMessage.error(error.response.data.msg)
} catch (err) {
ElMessage.error(error.message)
}
})
// 代码不要往后执行了
return Promise.reject(error)
}
// 如果有refresh_token,则请求获取新的 token
try {
const res = await axios({
method: 'PUT',
url: '/api/authorizations',
timeout: 10000,
headers: {
Authorization: `Bearer ${authorization.refresh_token}`,
},
})
// 如果获取成功,则把新的 token 更新到容器中
// console.log('刷新 token 成功', res)
store.commit('app/setToken', {
token: res.data.data.token, // 最新获取的可用 token
refresh_token: authorization.refresh_token, // 还是原来的 refresh_token
})
// 把之前失败的用户请求继续发出去
// config 是一个对象,其中包含本次失败请求相关的那些配置信息,例如 url、method 都有
// return 把 request 的请求结果继续返回给发请求的具体位置
return http(error.config)
} catch (err) {
// 如果获取失败,直接跳转 登录页
// console.log('请求刷新 token 失败', err)
const redirect = encodeURIComponent(window.location.href)
router.push(`/login?redirect=${redirect}`)
// 清除token
store.dispatch('app/clearToken')
return Promise.reject(error)
}
}
// console.dir(error) // 可在此进行错误上报
ElMessage.closeAll()
try {
ElMessage.error(error.response.data.msg)
} catch (err) {
ElMessage.error(error.message)
}
return Promise.reject(error)
}
)
/**
* Get请求
* @param url 请求地址
* @param params 参数
* @returns {Promise}
*/
export function get (url, params) {
return new Promise((resolve, reject) => {
axios.get(url, {
params: params
}).then(res => {
resolve(res.data)
}).catch(error => {
reject(error.data)
})
})
}
// 设置POST请求头,告诉服务器请求主体的数据格式:a=aaaa&b=bbbb
// 需要导入 import qs from 'qs'
/**
* Post请求
* @param url 请求地址
* @param params 参数
* @returns {Promise}
*/
export function post (url, params) {
return new Promise((resolve, reject) => {
axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8' // 默认
axios.post(url, qs.stringify(params))
.then(res => {
resolve(res.data)
})
.catch(err => {
reject(err.data)
})
})
}
export function postJson (url, params) {
return new Promise((resolve, reject) => {
// axios.defaults.headers['Content-Type'] = 'Content-Type: application/json;charset=UTF-8'
axios.post(url, params)
.then(res => {
resolve(res.data)
})
.catch(err => {
reject(err.data)
})
})
}
/*
* 文件上传
* url:请求地址
* params:参数
* */
export function fileUpload (url, params) {
return new Promise((resolve, reject) => {
axios({
url: url,
method: 'post',
data: params,
headers: { 'Content-Type': 'multipart/form-data' }
}).then(res => {
resolve(res)
})
.catch(error => {
reject(error)
})
})
}
前端代码
单击
单击
单击
单击
单击
单击
单击
单击
import {post, postJson} from '@/utils/axios'
export default {
name: 'Demo',
setup () {
//服务器端输出结果: hc 1234
const fun1 = () => {
post('/api/user/login1', {
username: 'hc',
password: '1234'
}).then(res => {
console.info(res)
})
}
//服务器端输出结果: hc 1234
const fun2 = () => {
post('/api/user/login2', {
username: 'hc',
password: '1234'
}).then(res => {
console.info(res)
})
}
//服务器端输出结果:User{username='hc', password='1234'}
const fun3 = () => {
post('/api/user/login3', {
username: 'hc',
password: '1234'
}).then(res => {
console.info(res)
})
}
//服务器端输出结果:报错
//DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotSupportedException:
//Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported]
const fun4 = () => {
post('/api/user/login4', {
username: 'hc',
password: '1234'
}).then(res => {
console.info(res)
})
}
//服务器端输出结果:null null
const fun5 = () => {
postJson('/api/user/login1', {
username: 'hc',
password: '1234'
}).then(res => {
console.info(res)
})
}
//服务器端输出结果:DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MissingServletRequestParameterException:
//Required request parameter 'username' for method parameter type String is not present]
const fun6 = () => {
postJson('/api/user/login2', {
username: 'hc',
password: '1234'
}).then(res => {
console.info(res)
})
}
//服务器端输出结果:User{username='null', password='null'}
const fun7 = () => {
postJson('/api/user/login3', {
username: 'hc',
password: '1234'
}).then(res => {
console.info(res)
})
}
//服务器端输出结果:User{username='hc', password='1234'}
const fun8 = () => {
postJson('/api/user/login4', {
username: 'hc',
password: '1234'
}).then(res => {
console.info(res)
})
}
return { fun1, fun2, fun3, fun4, fun5, fun6, fun7, fun8 }
}
}
结果