인프런 커뮤니티 질문&답변

simjieun님의 프로필 이미지
simjieun

작성한 질문수

풀스택 리액트 라이브코딩 - 간단한 쇼핑몰 만들기

graphql 연동이 안되요ㅠㅠ

작성

·

374

0

섹션2의 MSW강의에서

graphql연동한이후부터 에러가 나서, 해결이 안되서 문의드리게되었습니다ㅠ(window환경입니다)

http://localhost:3000/products 호출시

화면 캡처 2022-11-15 131042.png

browser-ponyfill.js:518        POST http://localhost:3000/ 404 (Not Found)
react_devtools_backend.js:4026 Error: GraphQL Error (Code: 404): {"response":{"error":"","status":404,"headers":{"map":{"access-control-allow-origin":"*","connection":"keep-alive","content-length":"0","date":"Tue, 15 Nov 2022 04:03:57 GMT","keep-alive":"timeout=5","content-type":"text/xml"}}},"request":{"query":"query GET_PRODUCTS {\n  id\n  imageUrl\n  price\n  title\n  description\n  createdAt\n}","variables":{}}}

    at index.ts:497:11

    at step (graphql-ws.ts:280:1)

    at Object.next (graphql-ws.ts:280:1)

    at fulfilled (graphql-ws.ts:280:1)

콘솔로그에 위처럼 에러가 나옵니다ㅠ

vite.config.js

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  esbuild: {
    define: {
      this: "window",
    },
  },
  server:{
    host: 'localhost',
    port: 3000
  }
})
queryClient.ts

import { request, RequestDocument } from "graphql-request";
import { QueryClient  } from "react-query";

export const getClient = (() => {
    let client: QueryClient | null = null;
    return () => {
        if(!client) client = new QueryClient({
            defaultOptions:{
                queries: {
                    cacheTime: 1000 * 60 * 60 * 24,
                    staleTime: 1000 * 60,
                    refetchOnMount: false,
                    refetchOnReconnect: false,
                    refetchOnWindowFocus: false,
                }
            }
        });
        return client;
    }
})()

const BASE_URL = '/'

export const restFetcher = async ({
    method,
    path,
    body,
    params
} : {
    method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
    path: string;
    body?: { [key:string]: any }
    params?: { [key:string]: any }
}) => {
    try {
        let url = `${BASE_URL}${path}`
        const fetchOptions: RequestInit = {
            method,
            headers: {
                'Content-Type' : 'application/json',
                'Access-Control-Allow-Origin' : BASE_URL
            }
        }
        if(params) {
            const searchParams = new URLSearchParams(params)
            url += '?' + searchParams.toString()
        }
        if(body) fetchOptions.body = JSON.stringify(body)

        const res = await fetch(url, fetchOptions)
        const json = await res.json()
        return json
    } catch (err) {
        console.error(err)
    }
}

export const graphqlFetcher = (query: RequestDocument, variables={}) => request(BASE_URL, query, variables)

export const QueryKeys = {
    PRODUCTS: 'PRODUCTS',
}
graphql/product.ts

import { gql } from 'graphql-tag'

export type Product = {
    id: string
    imageUrl: string
    price: number
    title: string
    description: string
    createdAt: string
}

export type Products = {
    products: Product[]
}

const GET_PRODUCTS = gql`
  query GET_PRODUCTS {
    id
    imageUrl
    price
    title
    description
    createdAt
  }
`

export const GET_PRODUCT = gql`
  query GET_PRODUCT($id: string) {
    id
    imageUrl
    price
    title
    description
    createdAt
  }
`

export default GET_PRODUCTS
/pages/products/index.tsx


import { useQuery } from "react-query"
import ProductItem from "../../components/product/item"
import { graphqlFetcher, QueryKeys } from "../../queryClient"
import GET_PRODUCTS, { Products } from "../../graphql/products";

const ProductList = () =>  {
    const { data } = useQuery<Products>(QueryKeys.PRODUCTS, ()=> graphqlFetcher(GET_PRODUCTS))

    console.log(data);
    return (
        <div>
            <h2>상품목록</h2>
            <ul className="products">
                {data?.products?.map(product => (
                    <ProductItem {...product} key={product.id} />
                ))}
            </ul>
        </div>
    )
}

export default ProductList

답변 1

0

정재남님의 프로필 이미지
정재남
지식공유자

mocks 폴더에 handler가 제대로 등록되어 있나요?
그밖에 의심가는 부분이 많아 즉각 답을 드리긴 어려울것 같은데,
깃헙에 코드 푸시하고 링크를 남겨주시면 저도 한 번 살펴볼게요.

simjieun님의 프로필 이미지
simjieun
질문자

https://github.com/simjieun/shopping-mall

github 주소입니다! 감사합니다 :)

정재남님의 프로필 이미지
정재남
지식공유자

음.. 제 컴퓨터에서는 너무 잘 실행되고 있네요;
원격으로 함께 보는편이 나을것 같아요. 아래 링크로 연락 주세요!

https://open.kakao.com/me/royjung

simjieun님의 프로필 이미지
simjieun

작성한 질문수

질문하기