Как получить заголовки ответа от WP REST API в Next. js? - PullRequest
0 голосов
/ 18 января 2020

Я получаю некоторые данные из WP REST API в Next. js с Isomorphi c unfetch , как я могу получить заголовки ответа?

import fetch from 'isomorphic-unfetch';

class Blog extends React.Component {
    static async getInitialProps() {
        const res = await fetch('https://wordpress.org/news/wp-json/wp/v2/posts');
        const data = await res.json();
        return { 
            res: res,
            data: data
        };
    }

    render() {
        console.log(this.props.res)
        console.log(this.props.data)
        return (
            <h1>Blog</h1>
        )
    }
}

Я не вижу ничего доступного в консоли enter image description here

, но когда я открываю url in, появляются заголовки браузер enter image description here

1 Ответ

1 голос
/ 18 января 2020

res.headers возвращает все заголовки в соответствии с this . Вы можете использовать res.headers.get ('x-wp-total'), чтобы получить значение, а затем вернуть его в функцию getInialProps.

import fetch from 'isomorphic-unfetch';

class Blog extends React.Component {
    static async getInitialProps() {
        const res = await fetch('https://wordpress.org/news/wp-json/wp/v2/posts');
        const data = await res.json();
        return { 
            res: res,
            data: data,
            wpTotal: res.headers.get('x-wp-total')
        };
    }

    render() {
        console.log(this.props.wpTotal)
        console.log(this.props.data)
        return (
            <h1>Blog</h1>
        )
    }
}
...