微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Graphql 端点在 insominia 和 postman 中工作,但在尝试获取数据时不在 react 应用程序上工作有什么建议么?

如何解决Graphql 端点在 insominia 和 postman 中工作,但在尝试获取数据时不在 react 应用程序上工作有什么建议么?

嗨,我对反应、spring-boot 和 graphql 很陌生。

我一直致力于构建一个反应网络应用程序的项目,该应用程序应该调用 graphql 端点来获取数据。所以我用 graphql 运行我的 spring-boot 项目, /graphiql 端点工作但 /graphql 没有。但是我尝试使用 insomnia 和 postman 获取数据,并且两者都能够从 /graphql 端点获取数据。

现在我的问题来了,我试图从我的反应应用程序中获取数据,但即使添加了 chrome 扩展,我仍然收到 CORS 错误。我不知道自己做错了什么,因为我遵循了本教程 (https://www.graphql-java.com/tutorials/getting-started-with-spring-boot/)。

我本来想,既然它与 Postman 和 Insomnia 一起工作,它也应该与我的 react 应用程序一起工作。关于我做错了什么的任何建议。

这是我的 GraphQLDataFetcher 类:

@Component
public class GraphQLDataFetcher {

@Autowired
private DAOContentSource daoContentSource;

public List<contentSource> getContentSource() throws IdException {

        try {
            return daoContentSource.list();
        }
        catch (Exception e){
            throw new IdException(e.getMessage());
        }
}


public DataFetcher<List<contentSource>> getAllContentSource() {
        return dataFetchingEnvironment -> getContentSource();
}

这是我的 GraphQLProviderClass:

@Component
public class GraphQLProvider {

    private GraphQL graphQL;

    @Autowired
    private GraphQLDataFetcher dataFetcher;

    @Bean
    public GraphQL graphQL() {
        return graphQL;
    }

    
    @postconstruct
    public void init() throws IOException {
        final Resource resource = new ClassPathResource("schema.graphql");
        String sdl = null;
        try {
            sdl = Files.readString(resource.getFile().toPath());
        } catch (IOException e) {
            e.printstacktrace();
        }
        GraphQLSchema graphQLSchema = buildSchema(sdl);
        this.graphQL = GraphQL.newGraphQL(graphQLSchema).build();
    }

    private GraphQLSchema buildSchema(String sdl) {
        TypeDeFinitionRegistry typeRegistry = new SchemaParser().parse(sdl);
        RuntimeWiring runtimeWiring = buildWiring();
        SchemaGenerator schemaGenerator = new SchemaGenerator();
        return schemaGenerator.makeExecutableSchema(typeRegistry,runtimeWiring);
    }


    
    private RuntimeWiring buildWiring() {
        return RuntimeWiring.newRuntimeWiring()
                .type(TypeRuntimeWiring.newTypeWiring("Query").dataFetcher("contentSource",dataFetcher.getAllContentSource()))
                .build();
    }

    
    
}

这是我的主要内容

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}

Build.gradle:

plugins {
    id 'org.springframework.boot' version '2.5.1'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jdbc'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.json:json:20171018'
    implementation 'junit:junit:4.13.1'
    implementation 'junit:junit:4.13.1'
    implementation 'junit:junit:4.13.1'
    implementation 'com.graphql-java:graphql-java:11.0' // NEW
    implementation 'com.graphql-java:graphql-java-spring-boot-starter-webmvc:1.0' // NEW
    implementation 'com.google.guava:guava:26.0-jre' // NEW
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.projectlombok:lombok:1.18.18'
    runtimeOnly 'MysqL:mysql-connector-java'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

test {
    useJUnitPlatform()
}

现在我的反应应用程序: App.js:

import './App.css';
import React from "react";
import axios from "axios";
import { useQuery } from "react-query";

const endpoint = "http://localhost:8080/graphql";
const QUERY = `
    {
        contentSource{
            name
        }
    }
`;

export default function App() {
  const { data,isLoading,error } = useQuery("contentSource",() => {
    return axios({
      url: endpoint,method: "POST",data: {
        query: QUERY
      }
    }).then(response => response.data.data);
  });

  if (isLoading) return "Loading...";
  if (error) return <pre>{error.message}</pre>;

  return (
      <div>
        <h1>Sample Text</h1>
        <ul>
          {data.contentSource}
        </ul>
      </div>
  );
}

和 Index.js:

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { QueryClient,QueryClientProvider } from "react-query";

const client = new QueryClient();

const rootElement = document.getElementById("root");
ReactDOM.render(
    <QueryClientProvider client={client}>
        <App />
    </QueryClientProvider>,rootElement
);

尝试通过调用 /graphql 端点获取时遇到的错误。 它应该在浏览器上显示“网络错误”。 并在控制台上显示

Access to XMLHttpRequest at 'http://localhost:8080/graphql' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我在 Insomnia 中通过点击此端点 (localhost:8080/graphql) 尝试的查询,该查询正在运行

{"query":"{contentSource{name}}"}

获取以下数据:

{
  "data": {
    "contentSource": [
      {
        "name": "EPG"
      },{
        "name": "VOD"
      },{
        "name": "PVR"
      }
    ]
  }
}

我知道我的代码很糟糕,但我花了 2 天半的时间试图让它工作,所以我很乐意接受一些建议!!!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?