这是我的App.js文件。我在这里运行查询。
我使用apollo客户端而不是apollo-boost。
import React, { useEffect } from "react";
import { useQuery } from "react-apollo";
import gql from "graphql-tag";
const MY_QUERY = gql`
query {
getAllSalons {
id
displayName
email
}
}
`;
const App = (props) => {
const { data, loading, error } = useQuery(MY_QUERY);
useEffect(() => console.log("-------", data), [data]);
useEffect(() => console.log("-------", error), [error]);
return (
<div className="App">
<h1>KOMB COLLECTION</h1>
{loading ? <h2>Loading...</h2> : <h2>Data :)</h2>}
</div>
);
}
这是我在index.js文件中设置apollo客户端的方法
我在阿波罗客户端中设置了身份验证。
这里是所有进口
import ApolloClient from "apollo-client";
import { ApolloProvider } from "react-apollo";
import { createHttpLink } from "apollo-link-http";
import { setContext } from "apollo-link-context";
import { InMemoryCache } from "apollo-cache-inmemory";
我仅通过此端点无法获取错误,但是它可以工作 在Postman中可以正常使用,并且另一个端点与此代码配合使用也很好。
const httpLink = createHttpLink({
uri: "http://13.125.142.93:3001/graphql",
});
const authLink = setContext((_, { headers }) => {
const token = localStorage.getItem("token");
return {
headers: {
...headers,
Authorization: token ? token : "",
},
};
});
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache(),
});
ReactDOM.render(
<ApolloProvider client={client}>
<App />
</ApolloProvider>,
document.getElementById("root")
);
我是graphql的新手,不知道如何处理此错误。另外,我也找不到任何文档。
我在控制台上收到此错误
Access to fetch at 'http://13.125.142.93:3001/graphql' from origin
'http://localhost:3000' has been blocked by CORS policy: Response to
preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. If an opaque response serves your needs, set the request's
mode to 'no-cors' to fetch the resource with CORS disabled.
答案 0 :(得分:0)
发生此错误是因为后端没有针对cors的配置。在后端配置cors,一切都会正常运行