简体   繁体   中英

Fetch POST Content-Type not change, when header is set on Options

I follow the example in https://scotch.io/tutorials/create-a-custom-usefetch-react-hook , to perform a fetch. All works.

I change it slightly to make a POST with 'Accept': 'application/json' and 'Content-Type': 'application/json' as per https://stackoverflow.com/a/29823632 . However, no matter how I post, it is still of Text/Html context type.

const useFetch = (url, body) => {
    const [response, setResponse] = React.useState(null);
    const [error, setError] = React.useState(null);

    React.useEffect(() => {
        const FetchData = async () => {
            try {
                const method = "POST"
                const headers = {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                };
                const options = {
                    method,
                    headers
                };
                if (body) options.body = JSON.stringify(body);
                const res = await fetch(url, options);
                const json = await res.json();
                setResponse(json);
            } catch (error) {
                setError(error);
            }
        };
        FetchData();
    }, []);
    return { response, error };
};

export default useFetch

What did I do wrong?

I'd say the answer depends on your request URL. Is your endpoint only capable of returning type text/html? What resource are you requesting?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM