Authorization : `Bearer ${token}`
형태로 토큰 넣어서 보내주기Client 생성 시 credentials 설정 추가(CORS 에러때문에)
import React from "react";
import { render } from "react-dom";
import { BrowserRouter } from "react-router-dom";
import App from "./src/App";
import {
ApolloClient,
ApolloProvider,
HttpLink,
InMemoryCache,
} from "@apollo/client";
import { createUploadLink } from "apollo-upload-client";
// 파일 업로드를 해야해서 createUploadLink 사용.
const httpLink = createUploadLink({
uri: "graphql 주소",
credentials: "same-origin", //CORS에러 처리하기 위해 추가
});
const client = new ApolloClient({
link: httpLink,
cache: new InMemoryCache(),
});// 클라이언트 인스턴스 생성
render(
<ApolloProvider client={client}>//프로바이더에 클라이언트 제공
<BrowserRouter>
<App />
</BrowserRouter>
</ApolloProvider>,
document.querySelector("#root")
);
graphql 요청보내는 곳에서 header 설정(context->headers-> [keyname] : token)
const [posting, { loading, error, data }] = useMutation(POSTING, {
context: {
headers: {
authorization: `Bearer ${window.localStorage.getItem("authToken")}`,
"Content-Type": "application/json",
},
},
});
const UPLOAD = gql`
mutation upload($file: Upload!) {
upload(file: $file) {
realName
fileId @export(as: "thumbnail")
originalName
}
}
`;
const POSTING = gql`
mutation createPost(
$title: String!
$tags: [String]!
$content: String
$thumbnail: ID
) {
createPost(
input: {
title: $title
tags: $tags
content: $content
thumbnail: $thumbnail
}
) {
postId
tags
}
}
`;
이제 gql안에 두 개의 뮤테이션을 넣어서 request를 보내면 된다.
gql구문에 두개의 뮤테이션을 한꺼번에 넣어서 실행하려고 했으나, 아래와 같은 에러가 뜨면서 실행되지 않았다.
react-apollo only supports a query, subscription, or a mutation per HOC. [object Object] had 0 queries, 0 subscriptions and 2 mutations. You can use 'compose' to join multiple operation types to a component
react-apollo 는 HOC 하나 당 하나의 뮤테이션/쿼리/서브스크립션 을 지원한다는 것이다. 그 다음에 친절하게도 여러개를 한꺼번에 실행하고 싶다면 여러 쿼리/뮤테이션/서브스크립션을 합쳐주는 'compose'를 사용하면 된다고 되어 있다.
-그래서 compose를 찾아보고 있는데,,아직은 정확히 어떻게 사용하는지 모르겠다. 보완해서 처리하기!
mutaion MUTAIONNAME($variableA:typeA,$varibleB:typeB){
A(variable:$variableA){
data
}
B(variable:$variableB){
data
}
}
위와 같은 형식으로 요청하면 잘만 실행된다. 내가 한 실수는 A와 B앞에도 mutation을 붙여버린 것,,!
원래 내부에선 mutation/query 안 붙이는데 무슨 정신으로 붙인건지 모르겠다.