uni-app中的解决办法

修改manifest.json文件

h5标签下添加转发配置

"devServer": {
    "https": false,
    "host": "0.0.0.0",
    "hotOnly": true,
    "port": 8000,
    "disableHostCheck": true,
    "proxy": {
        "/api": {
            // 后台服务器url
            "target": "http://localhost:7777",
            "changeOrigin": true,
            "secure": false,
            "ws": true,
            "pathRewrite": {
                // 重写路径 去除自定义的api字符串,和上方api是同一个
                "^/api": ""
            }
        }
    }
}

修改baseUrl

image-20221021170115122

去除ajax请求中的baseUrl

image-20221021170232600

请求成功

image-20221021170428785

spring boot中的解决方式

添加过滤器将自定义的header添加至Access-Control-Allow-Headers中

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

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

@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilterConfig implements Filter {

    @Override
    public void init(FilterConfig fc) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) resp;
        HttpServletRequest request = (HttpServletRequest) req;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        response.setHeader("Access-Control-Max-Age", "3600");
        // 添加自定义的header至下方
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization, Content-Type, Authorization, credential, X-XSRF-TOKEN, isToken, entIdList");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            // 预检请求返回200
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            chain.doFilter(request, response);
        }

    }

    @Override
    public void destroy() {
    }

}