zoukankan      html  css  js  c++  java
  • 基于Java服务的前后端分离解决跨域问题

    导语:解决跨域问题,前后端都增加相应的允许跨域的代码段即可。

    一、后端增加允许跨域的代码,可以在具体controler层加,最好是在filter中添加,这样添加一次就够了,不用在每个controler中都添加了,代码截图如下:

    代码如下:

    response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
    //指定本次预检请求的有效期,单位为秒
    response.setHeader("Access-Control-Max-Age", "86400");
    //如果存在自定义的header参数,需要在此处添加,逗号分隔
    response.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, " +
    "Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token");
    //允许跨域请求中携带cookie
    response.setHeader("Access-Control-Allow-Credentials", "true");
    response.setHeader("XDomainRequestAllowed","1");

    二、前端增加允许跨域的代码,这里使用的ajax.代码截图如下

     代码如下:

    $.ajax({
      url: "http://192.168.10.23:8080/hms/jkpgJkzd.do?action=getMbsdList",
      type: "get",
      crossDomain: true,
      xhrFields: {
        withCredentials: true
      },
      dataType: "json",
      data: {
        "yngrbsh":"31010920090306250337209",
        "pglsh":"157a0a07-73e9-450a-b835-3f396b3b7acb",
        "jbdms":"JB_GXY;JB_NCZ;JB_TNB_YH"
      },
      success: function (data) {
        alert(data);
        alert(JSON.stringify(data));
      }
    })

    至此完成!!!

  • 相关阅读:
    mysql表结构转hive表结构,字段映射脚本
    kafka 相关命令 偏移重置
    Specified key was too long; max key length is 767 bytes
    java IO 流关系图谱
    jvm 性能监控与linux常用命令
    jupiter的@TempDir 等不生效
    mysql 深度分页
    jedis的ShardedJedisPool链接池的扩容问题
    拜读《三国》看懂男人
    linux 性能优化
  • 原文地址:https://www.cnblogs.com/RoyalBlue/p/10451707.html
Copyright © 2011-2022 走看看