如何在React中使用GraphQL正文发送POST请求?

问题描述 投票:0回答:1

我正在尝试将POST请求发送到API。我正在React中开发客户端。

我已经成功地在Postman中测试了API,并收到了预期的响应数据。

我在我的代码中使用与Postman中相同的URL和GraphQL查询。这是我的代码:

import { useState, useEffect } from 'react';
import { API_URL } from '../../config';

export const usePlacesFetch = () => {
    const [state, setState] = useState({ places: [] });

    const fetchPlaces = async () => {
        const query = `query Places {
                places {
                    id
                    name
                    location {
                        latitude
                        longitude
                    }
                }
            }`;

        try {
            const response = await fetch(API_URL, {
                method: 'post',
                body: query,
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            console.log('RESPONSE', response);
        } catch (error) {
            console.error('ERROR', error);
        }
    };

    useEffect(() => {
        fetchPlaces();
    }, []);

    return [{ state }, fetchPlaces];
};

邮递员中我的回复正文如下:

{
    "data": {
        "places": [
            {
                "id": "XXXXX",
                "name": "XXXXX",
                "location": {
                    "latitude": XX.XXXXXXX,
                    "longitude": XX.XXXXXXX
                }
            },
            {
                "id": "XXXXX",
                "name": "XXXXX",
                "location": {
                    "latitude": XX.XXXXXXX,
                    "longitude": XX.XXXXXXX
                }
            }
        ]
    }
}

当我运行客户端并发出请求时,我会在控制台中得到以下结果:

POST http://api.xxxxxx.dk/ 400 (Bad Request)

RESPONSE 
Response {type: "cors", url: "http://api.xxxxxx.dk/", redirected: false, status: 400, ok: false, …}
body: (...)
bodyUsed: false
headers: Headers {}
ok: false
redirected: false
status: 400
statusText: "Bad Request"
type: "cors"
url: "http://api.xxxxxx.dk/"
__proto__: Response

如何正确发出请求,以便获得与邮递员获得的数据相同的数据?

reactjs graphql fetch bad-request
1个回答
0
投票

您需要stringify包含query的主体。

const response = await fetch(API_URL, {
                method: 'post',
                body: JSON.stringify({
                  query
                }),
                headers: {
                    'Content-Type': 'application/json'
                }
            });
© www.soinside.com 2019 - 2024. All rights reserved.