2

我正在尝试使GraphQL Java 服务器与 GraphiQL 服务器一起工作。

使用在本地运行的 GraphiQL,我提交了一个带有以下参数的查询:

GraphiQL 查询及其结果

我的 Spring 控制器(从此处复制)如下所示:

@Controller
@EnableAutoConfiguration
public class MavenController {
    private final MavenSchema schema = new MavenSchema();
    private final GraphQL graphql = new GraphQL(schema.getSchema());
    private static final Logger log = LoggerFactory.getLogger(MavenController.class);

    @RequestMapping(value = "/graphql", method = RequestMethod.OPTIONS, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Object executeOperation(@RequestBody Map body) {
        log.error("body: " + body);
        final String query = (String) body.get("query");
        final Map<String, Object> variables = (Map<String, Object>) body.get("variables");
        final ExecutionResult executionResult = graphql.execute(query, (Object) null, variables);
        final Map<String, Object> result = new LinkedHashMap<>();
        if (executionResult.getErrors().size() > 0) {
            result.put("errors", executionResult.getErrors());
            log.error("Errors: {}", executionResult.getErrors());
        }
        log.error("data: " + executionResult.getData());
        result.put("data", executionResult.getData());
        return result;
    }
}

理论上,executeOperation应该在我在 GraphiQL 中提交查询时调用。不是,我在控制台输出中看不到日志语句。

我在做什么错?MavenController.executeOperation当在 GraphiQL 中提交查询时,如何确保调用 ?

更新 1(13.01.2017 13:35 MSK):这是有关如何重现错误的教程。我的目标是创建一个基于 Java 的 GraphQL 服务器,我可以使用 GraphiQL 与之交互。如果可能的话,这应该在本地工作。

我已经读过,为了做到这一点,以下步骤是必要的:

  1. 设置 GraphQL 服务器。这方面的一个例子可以在这里找到https://github.com/graphql-java/todomvc-relay-java。该示例使用 Spring Boot,但您可以使用任何您喜欢的 HTTP 服务器来实现它。
  2. 设置 GraphiQL 服务器。这有点超出了这个项目的范围,但基本上你需要在上面的步骤 1 中让 GraphiQL 与服务器对话。它将使用自省来加载模式。

我检查了项目todomvc-relay-java,根据我的需要对其进行了修改并将其放入目录E:\graphiql-java\graphql-server中。您可以在此处下载包含该目录的存档。

第 1 步:安装 Node.JS

第2步

去那里E:\graphiql-java\graphql-server\appnpm install

第 3 步

npm start从同一目录运行。

第4步

去那里E:\graphiql-java\graphql-servergradlew start

第 5 步

运行docker run -p 8888:8080 -d -e GRAPHQL_SERVER=http://localhost:8080/graphql merapar/graphql-browser-docker

Docker 来源:graphql-browser-docker

第 6 步

在禁用 XSS 检查的情况下启动 Chrome,例如"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --args --disable-xss-auditor. 一些消息来源声称您必须杀死所有其他 Chrome 实例才能使这些参数生效。

第 7 步

在该浏览器中打开http://localhost:8888/ 。

第 8 步

尝试运行查询

{ allArtifacts(group: "com.graphql-java", name: "graphql-java") { group name version } }

实际结果:

1) Chrome控制台Fetch API cannot load http://localhost:8080/graphql. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8888' is therefore not allowed access. The response had HTTP status code 403. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.选项卡中的错误: .

中的错误

2) Chrome网络选项卡中的错误:

中的错误

更新 2 (14.01.2017 13:51):目前,CORS 在 Java 应用程序中的配置方式如下。

主类:

@SpringBootApplication
public class Main {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(Main.class, args);
    }

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry
                        .addMapping("/**")
                        .allowedMethods("OPTIONS")
                        .allowedOrigins("*")
                        .allowedHeaders(
                                "Access-Control-Request-Headers",
                                "Access-Control-Request-Method",
                                "Host",
                                "Connection",
                                "Origin",
                                "User-Agent",
                                "Accept",
                                "Referer",
                                "Accept-Encoding",
                                "Accept-Language",
                                "Access-Control-Allow-Origin"
                        )
                        .allowCredentials(true)
                        ;
            }
        };
    }
}

WebSecurityConfigurerAdapter子类:

@Configuration
@EnableWebSecurity
public class SpringWebSecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        System.out.println("SpringWebSecurityConfiguration");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("OPTIONS");
        source.registerCorsConfiguration("/**", config);
        http
                .addFilterBefore(new CorsFilter(source), ChannelProcessingFilter.class)
                .httpBasic()
                .disable()
                .authorizeRequests()
                    .anyRequest()
                    .permitAll()
                .and()
                .csrf()
                    .disable();
    }
    @Override
    public void configure(WebSecurity web) throws Exception {
    }
}

控制器:

@Controller
@EnableAutoConfiguration
public class MavenController {
    private final MavenSchema schema = new MavenSchema();
    private final GraphQL graphql = new GraphQL(schema.getSchema());
    private static final Logger log = LoggerFactory.getLogger(MavenController.class);

    @CrossOrigin(
            origins = {"http://localhost:8888", "*"},
            methods = {RequestMethod.OPTIONS},
            allowedHeaders = {"Access-Control-Request-Headers",
            "Access-Control-Request-Method",
            "Host",
            "Connection",
            "Origin",
            "User-Agent",
            "Accept",
            "Referer",
            "Accept-Encoding",
            "Accept-Language",
             "Access-Control-Allow-Origin"},
            exposedHeaders = "Access-Control-Allow-Origin"
             )
    @RequestMapping(value = "/graphql", method = RequestMethod.OPTIONS, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Object executeOperation(@RequestBody Map body) {
        [...]
    }
}

MavenController.executeOperation是当我在 GraphiQL 中发出查询请求时应该调用的方法。

更新3(15.01.2017 22:05):尝试使用CORSFilter,新的源代码在这里。没有结果,我仍然收到“无效的 CORS 响应”错误。

4

3 回答 3

1

问题在于应用程序中.allowedMethods("OPTIONS")配置的使用。

OPTIONS使用请求方法发送设计的飞行前请求。

Access-Control-Request-Method 由浏览器自动添加,allowedMethods属性实际上控制实际请求允许使用的请求方法。

文档中,

Access-Control-Request-Method 标头作为预检请求的一部分通知服务器,当实际请求发送时,它将使用 POST 请求方法发送。

所以它是POST方法,并且请求失败,因为您仅OPTIONS在验证完成时才允许。

因此更改allowedMethods*将匹配POST实际请求的浏览器设置请求方法。

完成上述更改后,您将获得 405,因为您的控制器仅允许OPTIONS您的POST请求。

因此,您需要更新控制器请求映射以允许 POST 以在飞行前请求之后使实际请求成功。

示例响应:

{
    "timestamp": 1484606833696,
    "status": 500,
    "error": "Internal Server Error",
    "exception": "graphql.AssertException",
    "message": "arguments can't be null",
    "path": "/graphql"
}

我不确定您是否在太多地方设置了 CORS 配置。我只需要更改.allowedMethodsspring 安全配置中的,使其按照我描述的方式工作。所以你可能想调查一下。

于 2017-01-16T22:08:00.020 回答
1

前段时间我遇到了同样的问题,我通过创建自己的 cors fiter bean 解决了这个问题。

例子:

public class CORSFilter implements Filter {

@Override
public void init(FilterConfig filterConfig) throws ServletException {

}

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
    response.setHeader("Access-Control-Allow-Credentials", "true");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, PUT, OPTIONS");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "accept, access-control-allow-origin, authorization, content-type");

    if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
        response.setStatus(HttpServletResponse.SC_OK);
    } else {
        chain.doFilter(req, res);
    }
}

@Override
public void destroy() {

}

}

我在我的配置类中定义了它:

@Bean(name = "corsFilter")
@Order(Ordered.HIGHEST_PRECEDENCE)
public CORSFilter corsFilter() {
    return new CORSFilter();
}

最后在我的 servlet 启动配置中定义它:

servletContext.addFilter("corsFilter", new DelegatingFilterProxy("corsFilter")).addMappingForUrlPatterns(null, false, "/*");

PS希望这会对你有所帮助。

于 2017-01-14T22:32:59.150 回答
1

您必须配置 Spring 调度程序 servlet ( http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/DispatcherServlet.html ) 来处理 OPTIONS。

通过 XML,您应该这样做:

  <servlet>
    <servlet-name>yourSpringSvltname</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>dispatchOptionsRequest</param-name>
      <param-value>true</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

通过 Java 配置:

 public class MyWebAppInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext container) {
      XmlWebApplicationContext appContext = new XmlWebApplicationContext();
      appContext.setConfigLocation("/WEB-INF/spring/dispatcher-config.xml");

      ServletRegistration.Dynamic dispatcher =
        container.addServlet("dispatcher", new DispatcherServlet(appContext));
dispatchersetDispatchOptionsRequest(true);
      dispatcher.setLoadOnStartup(1);
      dispatcher.addMapping("/");
    }

 }
于 2017-01-11T12:15:28.297 回答