【问题标题】:How to get response headers from WP REST API in Next.js?如何从 Next.js 中的 WP REST API 获取响应标头?
【发布时间】:2020-01-19 04:42:13
【问题描述】:

我正在使用 Isomorphic unfetch 从 Next.js 中的 WP REST API 获取一些数据,我如何获取响应标头?

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>
        )
    }
}

我在控制台 中看不到任何可用的内容@

但是当我在浏览器 中打开url 时,标题就在那里

【问题讨论】:

    标签: reactjs wordpress next.js


    【解决方案1】:

    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>
            )
        }
    }
    

    【讨论】:

    • 不幸的是我没有定义,我只能在 this.props.res 中访问大小和超时
    • 直到现在我才看到您编辑的帖子。谢谢,这样我确实得到了价值!
    • 我收到错误,因为response.headers.get 不是函数。就我而言,我需要在删除之前获取响应,并且 GET 响应标头包含标记值。
    • @Marko 遇到相关问题,我必须在进一步的 API 调用中传递标头。你能在这里看看吗stackoverflow.com/questions/69678380/…
    猜你喜欢
    • 2021-04-25
    • 1970-01-01
    • 2013-05-28
    • 1970-01-01
    • 2017-11-24
    • 2016-12-21
    • 1970-01-01
    • 1970-01-01
    • 2016-09-02
    相关资源
    最近更新 更多