前后端分离爬坑-JAVA后端解决跨域问题

1.新建interceptor包并新建CorsConfig类,直接贴代码;

package com.springboot.demo.interceptor;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 跨域请求filter
 */
@Configuration
public class CorsConfig {
    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setOrder(0);
        registrationBean.setName("CorsFilter");
        registrationBean.addUrlPatterns("/*");
        registrationBean.setFilter(new Filter() {
            @Override
            public void init(FilterConfig filterConfig) throws ServletException {
            }

            @Override
            public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
                HttpServletRequest httpRequest = (HttpServletRequest) request;
                HttpServletResponse httpResponse = (HttpServletResponse) response;
                httpResponse.setHeader("Access-Control-Allow-Origin", httpRequest.getHeader("Origin"));
                httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
                httpResponse.setHeader("Access-Control-Max-Age", "0");
                httpResponse.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,Access-Control-Allow-Headers , token, sid");
                httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
                httpResponse.setHeader("XDomainRequestAllowed", "1");
                chain.doFilter(request, response);
            }
            @Override
            public void destroy() {
            }
        });
        return registrationBean;
    }

}
复制代码

2.提取服务端地址进行封装

(function(root){

    //Nginx通用请求地址:解决前后端分离跨域问题
    root.BaseUrl = 'http://localhost:8888/';
}(this));
复制代码

3.修改前端ajax请求

$.ajax({
        url: BaseUrl + 'user/createUser',
        type: "post",
        data: ajaxdata,
        dataType: "json",
        success: function (data) {
          if (data.message=="success"){
            alert("注册成功")
          }
        }
      });
复制代码

跨域问题从后端解决,脱离NGINX。 ♪(^∇^*)

转载于:https://juejin.im/post/5c86932451882501ca6e268a

你可能感兴趣的:(前后端分离爬坑-JAVA后端解决跨域问题)