아폴로에서 레일스 백엔드에서 콘텐츠를 가져 오는 중 실망한 문제가 발생했습니다. 이 문제는 아폴로 프로젝트에서 CORS 사용과 관련하여 해결되는 것으로 보입니다.Apollo 및 GraphQL CORS
기술
- 아폴로 클라이언트 : 1.9.3
- graphql : 0.11.7
- 반응 : 15.6.1
- 반응 - 아폴로 : 1.4.16
cors.rb
(210 개)Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins `*`
resource '*',
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head]
end
end
레일은 curl
요청을 할 수있는이 백엔드 포트 (3001)rails s -p 3001
에서 실행되고, 이것은 다시 반환 모든 것이
작업 컬
curl -X POST -H "Content-Type: application/json" -d '{"query": "{users{first_name}}"}' http://localhost:3001/graphql
을 기대 작품으로 예상 데이터
그래서 Apollo와 응용 프로그램의 프론트 엔드에 대한 문제가 있습니다.
이 오류를
Failed to load http://localhost:3001/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:8080 ' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
응용 프로그램을 반환 App.jsx
import React, { Component } from 'react';
import gql from 'graphql-tag';
import { graphql } from 'react-apollo';
class App extends Component {
render() {
console.log(this.props);
return (
<div>Application</div>
);
}
}
const query = gql`
{
users {
first_name
}
}
`;
export default graphql(query)(App);
import React from 'react';
import ReactDOM from 'react-dom';
import ApolloClient from 'apollo-client';
import { ApolloProvider, createNetworkInterface } from 'react-apollo';
import App from './containers/App.jsx';
const client = new ApolloClient({
networkInterface: createNetworkInterface({
uri: 'http://localhost:3001/graphql', <<<<< There is a different endpoint then the standard 'graphql' which is why this is declared
})
});
ReactDOM.render(
<ApolloProvider client={client}>
<App />
</ApolloProvider>,
document.getElementById('root')
);
을 index.jsx.
일반
Request URL:http://localhost:3001/graphql
Request Method:POST
Status Code:200 OK
Remote Address:[::1]:3001
Referrer Policy:no-referrer-when-downgrade
응답 헤더
CAC : jsx (변경 모드)
const client = new ApolloClient({
networkInterface: createNetworkInterface({
uri: 'http://localhost:3001/graphql',
opts: {
mode: 'no-cors'
}
})
});
이 요청을 보면 오류
Unhandled (in react-apollo) Error: Network error: Network request failed with status 0 - ""`
을 반환 he-Control : 최대 연령 = 0, 비공개, 다시 유효성을 검사해야 함 콘텐츠 형식 : application/json; 문자셋 = UTF-8 전송 - 인코딩 : 청크는 비바리 : 원산지를
요청 헤더
Accept:*/*
Connection:keep-alive
Content-Length:87
Content-Type:text/plain;charset=UTF-8 <<< I'm wondering if this needs to be application/json?
Host:localhost:3001
Origin:http://localhost:8080
Referer:http://localhost:8080/
User-Agent:Chrome/61
요청 페이로드
{query: "{↵ users {↵ first_name↵ __typename↵ }↵}↵", operationName: null}
operationName
:
null
query
:
"{↵ users {↵ first_name↵ __typename↵ }↵}↵"
나는 반응의 일종을 얻을했다 그래서 크롬 확장 프로그램을 설치하는 것입니다. Allow-Control-Allow-Origin: *
mode: 'no-cors'
이 제거되고이 확장자가 활성이면 데이터를 검색 할 수 있습니다.
아폴로 문서를 살펴보면이 주제를 많이 찾을 수 없습니다. Apollo Auth Header을 구현하려고 시도했지만 위와 동일한 오류가 발생했습니다.
내 Apollo 코드에서 이러한 오류의 원인은 무엇입니까? 문제를 해결하기위한 단계는 무엇입니까?
GitHub 문제 및 기타 Google 검색을 통해 검색하면 문제가 "해결되었거나"구현되지 않은 Apollo의 훨씬 오래된 버전입니다. 레일에 필요한 더 많은 구성이 경우를 대비 레일 태그에 루비를 추가
편집
. 조사했을 때 Apollo Client 문제가 발견됨 Network error: Network request failed with status 0 - ""이 문제는 백엔드 문제 때문에 OP에서 해결되었습니다.