【问题标题】:Spring boot does not receive headers from react jsSpring Boot 不接收来自 react js 的标头
【发布时间】:2018-09-30 17:20:32
【问题描述】:

我正在实现一个 ReactJs 应用程序。我正在使用 axios 调用使用 Spring Boot 构建的服务器端服务。我需要发送标题“授权:承载令牌值”。这是客户端代码:

var options = {
    withCredentials: true,
    headers: {'Authorization': 'Bearer token-value'}
};
axios.post('http://localhost:9090/services/list', null, options)
    .then((data) => {
        console.log(data);
    })
    .catch((error) => {
        console.error(error);
    });

这是 Spring Boot 控制器:

@RestController
public class ServiceController {

    private static final String AUTHORIZATION_HEADER_NAME = "Authorization";
    private static final String BEARER = "Bearer ";

    private static String getToken(HttpServletRequest request) {
        String header = request.getHeader(AUTHORIZATION_HEADER_NAME);
        if (header == null || header.trim().equals("")) {
            return null;
        }
        header = header.trim();
        if (!header.startsWith(BEARER)) {
            return null;
        }
        return header.substring(BEARER.length()).trim();
    }

    @GetMapping
    @RequestMapping(value = "/services/list", produces = "application/json", method = RequestMethod.POST)
    public ResponseEntity<?> getTargets(HttpServletRequest request, HttpServletResponse response) {
        String token = getToken(request);
        if (token == null) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
        DTOObject obj = goForTheBusinessObject(token);
        return new ResponseEntity<>(obj, HttpStatus.OK);
    }
}

这是 CORS 配置

@Configuration
public class RestConfig {
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("DELETE");
        config.addAllowedMethod("PUT");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}

如果我使用 curl 调用服务,我会得到预期的响应:

curl -X POST -H "Authorization: Bearer token-value" http://localhost:9090/services/list

如果我使用 post man 调用服务,我又得到了正确的答案。

但是当我执行 ReactJS 应用程序时,服务器永远不会收到“授权”标头。

请有人帮帮我!!

【问题讨论】:

    标签: reactjs spring-boot axios


    【解决方案1】:

    你正面临 CORS 问题,实现这个类来解决这个问题-

    @Component
    public class CorsFilter  implements WebFilter  {
    
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        if (exchange != null) {
            exchange.getResponse().getHeaders().add("Access-Control-Allow-Origin", "*");
            exchange.getResponse().getHeaders().add("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS");
            exchange.getResponse().getHeaders().add("Access-Control-Allow-Headers",
                    "DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range");
            exchange.getResponse().getHeaders().add("Access-Control-Max-Age", "1728000");
    
            if (exchange.getRequest().getMethod() == HttpMethod.OPTIONS) {
                exchange.getResponse().getHeaders().add("Access-Control-Max-Age", "1728000");
                exchange.getResponse().setStatusCode(HttpStatus.NO_CONTENT);
                return Mono.empty();
            } else {
                exchange.getResponse().getHeaders().add("Access-Control-Expose-Headers", "DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range");
                return chain.filter(exchange);
            }
    
        } else {
            return chain.filter(exchange);
        }
    
    }
    }
    

    有关 CORS 的更多信息,请访问this

    更新:要扫描组件,您可以执行以下操作-

    @ComponentScan(value = "com.pck", // cors filter package
        useDefaultFilters = false)
    public class MainClass {
        public static void main(String[] args) {
            ApplicationContext context = SpringApplication.
            run(MainClass.class, args);
        }
    }
    

    【讨论】:

    • 谢谢迪恩。我已经实现了你所说的。现在我的问题是 Spring Boot 没有找到该类。我在方法filter(ServerWebExchange exchange, WebFilterChain chain) 中写入了一条调试消息,并将新类包的名称添加到扫描仪中:@ComponentScan, @ServletComponentScan 并作为注释@SpringBootApplication 的参数,但没有为Spring Boot 加载CORS。有什么建议吗?...再次感谢。
    • 你试过了吗,@SpringBootApplication(scanBasePackages = { "com.pkg"})?
    • @RDV,我已经更新了答案。你可以试试这个,让我知道它是否有效?
    猜你喜欢
    • 1970-01-01
    • 2021-09-13
    • 2018-01-28
    • 1970-01-01
    • 1970-01-01
    • 2017-06-21
    • 2021-06-10
    • 2018-06-03
    • 1970-01-01
    相关资源
    最近更新 更多