解决vue-servlet数据传输时出现的跨域问题

这篇文章主要是记录本人在练习过程中碰到的跨域问题,主要分为两种:

第一种:使用axios进行数据传递时出现的跨域

要想解决这个跨域问题,需要前端和后端都添加相应的代码

后端需要添加的代码

        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html; charset=utf-8");
        //        设置响应头允许ajax跨域访问
        resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        resp.setHeader("Access-Control-Max-Age", "3600");
        resp.setHeader("Access-Control-Allow-Headers", "token, Accept, Origin, X-Requested-With, Content-Type, Last-Modified");

这里的代码的主要的作用就是对请求头进行设置,尽可能的解除请求头的限制

前端需要添加的代码

我在网上查看了很多的方法,都说直接在后端添加上面的代码就行了,可是不知道是不是我前端用vue的问题,即使我加上上面的代码问题还是没有解决,但最后我在前端显示的加上请求头的参数后问题就解决了,主要时添加了Content-Type
代码如下

// create an axios instance
// 这里封装一个axios实例
const service = axios.create({
  // 直接将这里的baseurl改为后端的baseurl即可
  baseURL:"http://localhost/servlet_demo4_war_exploded", // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 ,// request timeout, 
 
  // 下面的代码设置传输数据的的编码方式,第一个讲道理时默认的才对但是不设置的话会出现跨域问题
  // headers: {"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"},
   headers: {"Content-Type": "multipart/form-data;charset=UTF-8"},
   dataType: "json"
})

第2中情况:使用upload进行图片上传后出现的跨域问题

后端需要添加的代码

同样后端要做的就是解除限制,代码和第一种情况的一致

        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html; charset=utf-8");
        //        设置响应头允许ajax跨域访问
        resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        resp.setHeader("Access-Control-Max-Age", "3600");
        resp.setHeader("Access-Control-Allow-Headers", "token, Accept, Origin, X-Requested-With, Content-Type, Last-Modified");

前端部分代码

前端部分需要修改的部分:
首先需要取消el-load的自动提交:并重写其http-request方法,因为如果直接将url放到action的参数跨域是解决不了的
代码如下:
html部分

 <el-upload
                ref="upload"
                class="avatar-uploader"
                :headers="headerObj"
                action=""
                name="file" 
                :http-request="handleUploadFile"        
                :show-file-list="false"
                :on-success="handleAvatarSuccess">
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>

js部分

        // 重写文件上传方法
        handleUploadFile (params) {
            let file = this.$refs.upload.uploadFiles.pop().raw;//这里获取上传的文件对象
            let formData = new FormData();
            formData.append("file",file);
			request({
				url:'/image-servlet',
				method:'post',
				headers:{'Content-Type':'multipart/form-data'},
				data:formData
			}).then(res=>{
				if(res.code==200){
				   this.imageUrl=res.img;
				}else{
					params.onError()
				}
			})
        },

第2步就是在vue.config中开启代理:

// vue.config.js
module.exports = {
   // 关闭语法检查
     lintOnSave:false,
     devServer: {
      proxy: {
        '/api': {
        //后端接口的baseurl
          target: ' http://localhost/servlet_demo4_war_exploded/',
          //是否允许跨域
          changeOrigin: true,
          pathRewrite: {
          //这里的作用是使用去掉api
              '^/api': ''
          }
      }
  }
}
}

pathRewrite的作用具体如下:
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值