项目场景:
提示:通过vue.axios向后端传送数组时候出现的问题
在这里强调一下并不是所有的has been blocked by CORS policy:NO 'Access-'Control-Allow-Originheader is present on the requested resource 都是跨域问题,也有可能会跟我们后端的代码有关,我看网上一堆都说是跨域问题让我思考问题都从跨域问题思考了,最后发现是后端出现问题。
问题描述:
在写一个老师出试卷的项目当中,老师需要在前端往后端传送数据(这个数据是一个数组)数据内容如下(以下代码中只需要了解data里面的数据以及publish_exam( JSON.stringify(this.question),this.$route.query.id) 其它代码只是为了让想学axios的同学了解下)
data(){
return{
//老师角色往question中记录问题,这里我初始化为1
question:[
{content:'1',A_selection:'1',B_selection:'1',C_selection:'1',D_selection:'1'},
{content:'1',A_selection:'1',B_selection:'1',C_selection:'1',D_selection:'1'},
{content:'1',A_selection:'1',B_selection:'1',C_selection:'1',D_selection:'1'},
{content:'1',A_selection:'1',B_selection:'1',C_selection:'1',D_selection:'1'},
{content:'1',A_selection:'1',B_selection:'1',C_selection:'1',D_selection:'1'}
],
que_num:1
}
}
vue.axios向后端传送question的代码如下
methods:{
finishPublish(){
publish_exam( JSON.stringify(this.question),this.$route.query.id).then(res=>{
console.log(res);
this.$router.push({
path:"/home_teacher/"+this.$route.query.id,
query:{
id:this.$route.query.id,
isLogin:this.$route.query.isLogin
}
})
})
}
//publish_exam如下
import{request} from "./request";
export function publish_exam(question,id) {
return request({
url:'/service/test/publish',
methods:'post',
params:{
question:question,
id:id
}
})
}
//request如下
import axios from 'axios'
export function request(config) {
// 1.创建axios的实例
const instance = axios.create({
baseURL: 'http://localhost:8088/eduWebBack_war_exploded/',
timeout: 3000
})
// 2.axios的拦截器
// 2.1.请求拦截的作用
instance.interceptors.request.use(config => {
return config
}, err => {
console.log(err);
})
// 2.2.响应拦截
instance.interceptors.response.use(res => {
return res.data
}, err => {
console.log(err);
})
// 3.发送真正的网络请求
return instance(config)
}
那么传到后端的时候(后端只是使用req.getParameter(“question”)都会出错)就会出现标题所带的错误,具体错误如下
原因分析:
最主要的原因还是我们前端使用JSON.stringify往后端直接传递JSON字符串,前提是使用vue框架。
解决方案:
1.将原本的JSON.stringify(this.question)改为qs.parse(JSON.stringify(this.question)),代码(原本代码见上面)如下
publish_exam( qs.parse(JSON.stringify(this.question)),this.$route.query.id)
不过友情提示使用qs的话需要先使用下面语句下载qs,并且还需要在<script>中引入
下载
npm install qs
引入
import qs from 'qs';
2.这样后端就能正常接收到一个JSON字符串了字符串如下:
可以发现到会有很多斜杠,这个时候我们就需要反串
3.反串需要先下载一个commons-lang包,下载地址在下面
commons-lang包下载地址,点一下前往
下载地方如下
下载后添加到库里就好了(既然都会vue了怎么添加到库就不用我教了吧,要的话私信)
4.commons-lang包下载完之后使用下面代码把JSON字符串进行反串
//获取前端JSON
String jsonString=req.getParameter("question");
//反串语句
String tmp= StringEscapeUtils.unescapeJava(jsonString);
反串结果如下
正常JSON应该如下所示
那么接下来要进行JSON规范化
5.JSON的规范代码(借鉴借鉴就好了)如下
jsonString="["+tmp.substring(2,tmp.length()-5)+"]";
规范结果如下所示
6.最后我们也能正常使用JSON转换为list的形式了,csdn上其它文章有教如何让JSON转换成list,这里我也不教了