最近接触到的vue项目,需要使用 SSR asyncData,遇到了一个问题需要使用并发,同时进行多个post请求。
await Promise.all可以实现并发请求,如果是get提交、或者post无参数提交不会遇到问题。
但是使用post提交,并且有参数,就会报415错误。
后端报错信息如下:
HttpMediaTypeNotSupportedException: Content type ‘application/x-www-form-urlencoded;charset=UTF-8’ not supported
需要设置$axios的post请求头, ‘Content-Type’: ‘application/json’,下面是我使用的一种方式。
主要是这一段:
$axios({
url: '/v4/article/ks/list',
method: 'post',
data: {pageNo: 1,
pageSize: 20,
orderBy: null,
orderDir: null,
searchMap: {
catId: route.query.catId ? route.query.catId : 33,
typeCodes: route.query.articleCats ? route.query.articleCats : ''
}},
headers: {
'Content-Type': 'application/json'
}
})
完整代码如下:
async asyncData ({ $axios, route }) {
let [request1Data, request2Data] = await Promise.all([
$axios({
url: '/v4/article/ks/list',
method: 'post',
data: {pageNo: 1,
pageSize: 20,
orderBy: null,
orderDir: null,
searchMap: {
catId: route.query.catId ? route.query.catId : 33,
typeCodes: route.query.articleCats ? route.query.articleCats : ''
}},
headers: {
'Content-Type': 'application/json'
}
}),
$axios({
url: '/v4/article/getFirstType',
method: 'post',
data: {},
headers: {
'Content-Type': 'application/json'
}
})
])
return {
articleList: request1Data.data.data.list,
articleCount: request1Data.data.data.count,
isShowCatId: route.query.catId ? route.query.catId : 33,
articleTypeList: request2Data.data.data,
}
}