Spring引导不接收来自react js的头文件

时间:2018-04-20 04:33:37

标签: reactjs spring-boot axios

我实现了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应用程序时,服务器永远不会收到&#34;授权&#34;报头中。

请有人帮帮我!!

1 个答案:

答案 0 :(得分: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);
    }
}