vue.js+axios请求跨域问题、session丢失问题(已解决)

场景:实现生成图片验证码和检验验证码是否正确的功能;用的vue.js+axios请求

问题:

1:开发环境中前后端分离端口号不同导致跨域问题(403错误)

2:跨域解决后,前端用axios post方式请求后端(springmvc),后端拿不到参数

3:能拿到参数后后端报500错误,debug发现session为空(但是在生成验证码接口session是存在的),也就是在检测验证码是否正确的请求中session丢失

解决:

1:使用代理方式解决跨域:

    在config/index.js里边找到:

proxyTable: {      // 请求到/manage/code/check 现在会被代理到请求 http://localhost:8081/manage/code/check。
      '/manage': {//名字必须跟application context相同 否则404
        target: 'http://localhost:8081',
        changeOrigin: true               //  跨域
        // pathRewrite: {
        //   '^/manage': 'manage'
        // }
      }
    }

代理后的请求路径:checkImgUrl: '/manage/code/check'

注意:代理名要与application context相同;跨域changeOrigin: true;RewritePath,是将对资源的请求重定向到另一路径,使其不同于所请求 URL 指示的路径,看需求要不要加

2:axios post请求传参(对象

请求:
 
 
onSubmit(formName) {
  console.log(this.product);
  let book={
    bname:this.product.bname,
    author:this.product.author,
    img:this.product.img,
    brief:this.product.brief,
    publisher:this.product.publisher,
    ddprice:this.product.ddprice,
    price:this.product.price,
    categoryId:this.product.categoryId,
    status:'1'
  }
  this.$http.post(this.addUrl,book)
    .then((res)=>{
      console.log(res);
      if (res.data.code==1){
        this.$router.push("/toMain/productInfo");
        this.$message({
          type:'success',
          message:'图书添加成功',
          center: true
        })
      }else {
        this.$message.error("图书添加失败!");
      }
    })
}

(项目中登录竟然晕着脑袋写成post,后端是get自然取不到参数)

get请求:

 
 
this.$http.get(this.submitUrl, {
  params: {
    name: this.admin.username,
    pass: this.admin.pass
  }
})

3:问题在于请求路径不对

    首先看session为空,排除换浏览器、重启服务器导致session清空,想到session的唯一标识是sessionid,而sessionid存放在cookie中随请求携带,因此想到可能是请求头中的cookie携带sessionid不存在

    开始代理的代码:(错误示范)

    

// proxyTable: {
    //   '/api': {//
    //     target: 'http://localhost:8081',
    //     changeOrigin: true,                 
    //     pathRewrite: {
    //       '^/api': 'api'
    //     }
    //   }
    // },

使用:checkImgUrl: '/api/manage/code/check'

真正的session路径在/manage下,但是上面这个请求虽然被代理到http://localhosst:8081/manage接口,但是请求http://localhosst:8080/api/manage携带的cookie在/api路径,在/api路径找/manage下cookie自然找不到,就导致虽然能访问到接口但session为空

正确写法就是问题1中的写法,代理对象名与后台application· context相同!




猜你喜欢

转载自blog.csdn.net/menglinjie/article/details/80434600
今日推荐