欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

spring boot配合前端实现跨域请求访问

程序员文章站 2024-03-01 09:22:58
一.方法: 服务端设置respone header头中access-control-allow-origin 配合前台使用jsonp 继承webmvc...

一.方法:

  1. 服务端设置respone header头中access-control-allow-origin
  2. 配合前台使用jsonp
  3. 继承webmvcconfigureradapter 添加配置类

二.实例:

1.前端:因为我们用了前后端分离,前端用node服务器,node服务器再用了ajax反向代理请求到我的spring boot 服务器。其中node服务器也用了ajax发出请求所以也存在跨域的问题。具体代码:

 app.all(apiroot + '/*', proxy('127.0.0.1:' + proxyport, {
  forwardpath: function(req, res) {
   console.log('req: ', req, 'res; ', res);
   return require('url').parse(req.url).path;
  }
 }));

后台(用的是spring boot 1.3.7.release) :用了一个filter进行了身份验证同时进行了跨域处理,具体代码:

public class authfilter implements filter {
  //  @autowired
  //这个不能自动注入servlet和filter是被tomcat管理的
  private baseuserservice baseuserservice;
  private string[] excludepaths;

  @override
  public void init(filterconfig filterconfig) throws servletexception {
    system.out.println("initfilter");
    //不能在初始化中通过appliaction context获取因为这时候还没初始化application context
    //baseuserservice = springutils.getbean("baseuserservice", baseuserservice.class);
    excludepaths = new string[]{"/api/user/nologin", "/api/user/tokenerror", "/api/user/loginforeground",
        "/api/user/loginbackground", "/api/user/incorrectuserid"};
  }

  @override
  public void dofilter(servletrequest request, servletresponse response, filterchain chain) throws ioexception, servletexception {
    httpservletrequest httpservletrequest = (httpservletrequest) request;
    httpservletresponse httpservletresponse = (httpservletresponse) response;
    //这里填写你允许进行跨域的主机ip
    httpservletresponse.setheader("access-control-allow-origin", "*");
    //允许的访问方法
    httpservletresponse.setheader("access-control-allow-methods", "post, get, put, options, delete, patch");
    //access-control-max-age 用于 cors 相关配置的缓存
    httpservletresponse.setheader("access-control-max-age", "3600");
    httpservletresponse.setheader("access-control-allow-headers", "origin, x-requested-with, content-type, accept");
    string userid = request.getparameter("userid");
    string token = request.getparameter("token");
    //有token的                           `
    if (userid != null && token != null) {
      try {
        integer id = integer.parseint(userid);
        if (baseuserservice == null)
          baseuserservice = springutils.getbean("baseuserservice", baseuserservice.class);
        int status = baseuserservice.checklogin(id, token);
        if (status == 1) {
          chain.dofilter(request, response);
        } else if (status == 0) {
          httpservletresponse.sendredirect("/api/user/tokenerror");
        } else if (status == -2) {
          httpservletresponse.sendredirect("/api/user/incorrectuserid");
        } else {
          httpservletresponse.sendredirect("/api/user/nologin");
        }
      } catch (numberformatexception exception) {
        httpservletresponse.sendredirect("/api/user/incorrectuserid");
      }
    } else {
      string path = httpservletrequest.getservletpath();
      if (excludepath(path)) {
        chain.dofilter(request, response);
      } else {
        httpservletrequest.getrequestdispatcher("/api/user/nologin").forward(request, response);
      }
    }
//    ((httpservletresponse) response).addheader("access-control-allow-origin", "*");
//    corsfilter corsfilter=new corsfilter();

  }

  private boolean excludepath(string path) {
    for (int i = 0; i < excludepaths.length; i++) {
      if (path.equals(excludepaths[i]))
        return true;
    }
    return false;
  }

  @override
  public void destroy() {
    system.out.println("destroy method");
  }

}

这种方法还适用于servlet中,特别注意的是一定要在filter动作之前加上这句话,也就是在代码的最前面加上这个话。

跨域资源共享 cors 详解()

2.详细请看()
3.具体代码:

package edu.ecnu.yjsy.conf; 

import org.springframework.context.annotation.configuration; 
import org.springframework.web.servlet.config.annotation.corsregistry; 
import org.springframework.web.servlet.config.annotation.webmvcconfigureradapter; 

@configuration 
public class corsconfig extends webmvcconfigureradapter { 

  @override 
  public void addcorsmappings(corsregistry registry) { 
    registry.addmapping("/**") 
        .allowedorigins("*") 
        .allowcredentials(true) 
        .allowedmethods("get", "post", "delete", "put") 
        .maxage(3600); 
  } 

} 

这里有个坑spring boot 以前的版本这样设置可以用但是 我用的1.3.7.release spring boot 不能用,所以用第二种方式是万能的

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。