美文网首页
新增-后端跨域

新增-后端跨域

作者: wqjcarnation | 来源:发表于2021-06-24 10:41 被阅读0次

    前端程序

      login:function(){
        this.$axios.post("http://localhost:8081/javawebstudy/loginServlet")
        .then(res=>{
          console.log(res)
        })
        .catch(error=>{
          console.log(error)
        })
    
    
      }
    

    后端程序

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //指定请求的编码方式为utf-8
        request.setCharacterEncoding("utf-8");
        //指定响应的编码方式为utf-8
        response.setCharacterEncoding("utf-8");
        System.out.println(name);
        System.out.println(password);
        //指定内容格式为html
        response.setContentType("text/html");
        response.getWriter().append("<h1>成功</h1>");
    }
    

    现在请求无法,到达需要解决跨域问题

    每个servlet单独做跨域设置

         response.setHeader("Access-Control-Allow-Origin", "http://localhost:8082");
    

    跨域过滤器

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // TODO Auto-generated method stub
        // place your code here
        HttpServletResponse resp=(HttpServletResponse) response;
        
        // 允许跨域的主机地址,允许任意domain访问 
        //坑:前台axios设置withCredentials: true后,Access-Control-Allow-Origin的值不可以为*
        resp.setHeader("Access-Control-Allow-Origin", "http://localhost:8082");// 前端地址
        /* 允许跨域的请求头 */
        resp.setHeader("Access-Control-Allow-Headers", "*");
        /* 允许跨域的请求方法GET, POST, HEAD 等 */
        resp.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
        /* 重新预检验跨域的缓存时间 (s) */
        resp.setHeader("Access-Control-Max-Age", time + "");
        /* 是否携带cookie,session支持  同步的需要前端做一些配置*/
        resp.setHeader("Access-Control-Allow-Credentials", "true");  
        chain.doFilter(request, resp);
        
    }
    
    private final int time = 20 * 24 * 60 * 60;
    

    相关文章

      网友评论

          本文标题:新增-后端跨域

          本文链接:https://www.haomeiwen.com/subject/xfrwyltx.html