【问题标题】:How to display json values from api page to page in next.js?如何在 next.js 中从 api 页面到页面显示 json 值?
【发布时间】:2021-03-18 22:36:50
【问题描述】:

我有一个 api 页面 secured.js(我在其中详细说明用户会话数据)及其对应的普通页面 secured.js(我在其中显示来自api 页面)。

这是 api 页面 secured.js

const {google} = require('googleapis');
import fetch from 'isomorphic-unfetch'
import { getSession } from 'next-auth/client'

const secret = process.env.SECRET

export default async (req, res) => {
  const session = await getSession({ req });
  const token = JSON.stringify(session.token);

  var tokenUrl = `https://www.googleapis.com/youtube/v3/subscriptions?part=snippet%2CcontentDetails&mine=true&key=<key>&access_token=${token}`;
  tokenUrl = tokenUrl.replace(/"/g, '');
  const url = await fetch(tokenUrl);
  const data = await url.json();

  if (session) {
    res.send({ content: JSON.stringify(data.items) })
  } else {
    res.send({ error: 'You must be sign in to view the protected content on this page.' })
  }
}

这是正常的页面secured.js

import { useState, useEffect } from 'react'
import { useSession } from 'next-auth/client'
import Layout from '../components/layout'
import AccessDenied from '../components/access-denied'

export default function Page () {
  const [ session, loading ] = useSession()
  const [ content , setContent ] = useState()

  // Fetch content from protected route
  useEffect(()=>{
    const fetchData = async () => {
      const res = await fetch('/api/examples/protected')
      const json = await res.json()
      if (json.content) { setContent(json.content) }
    }
    fetchData()
  },[session])

  // When rendering client side don't display anything until loading is complete
  if (typeof window !== 'undefined' && loading) return null

  // If no session exists, display access denied message
  if (!session) { return  <Layout><AccessDenied/></Layout> }

  // If session exists, display content
  return (
    <Layout>
      <h1>Your favorite Channels</h1>
      <div>{content}</div>
    </Layout>
  )
}

&lt;Layout&gt; 内的 &lt;div&gt;{content}&lt;/div&gt; 输出从 api 页面检索到的 json 数据,我如何遍历该数据并在 ul li 中显示它?

我尝试用以下内容更改&lt;div&gt;{content}&lt;/div&gt;

<div>{content.map((id, sub) => (
        <li key={id}>
        <img class="img-rounded" src={sub.snippet.thumbnails.default.url} />
        <h4>{sub.snippet.title}</h4>
        </li>
      ))}</div>

但它说“内容”未定义。

json 看起来像这样在做console.log(data):

{
  kind: 'youtube#SubscriptionListResponse',
  etag: '9zUjByxqEbu9WrZxZ9KykymtKAQ',
  nextPageToken: 'CAUQAA',
  pageInfo: { totalResults: 14, resultsPerPage: 5 },
  items: [
    {
      kind: 'youtube#subscription',
      etag: 'N0uKZfzGEUkRStfyhc6leQJlbR4',
      id: 'I_5v-i46Mo0XuNIRp6SftSJ6E2HQ9f_2H___G6CgCbQ',
      snippet: [Object],
      contentDetails: [Object]
    },
    {
      kind: 'youtube#subscription',
      etag: 'oA4L_vI93bndMnvb9wdIcNTvRTs',
      id: 'I_5v-i46Mo0XuNIRp6SftelW2GFn1r_bjGM3stfrHHk',
      snippet: [Object],
      contentDetails: [Object]
    },
    {
      kind: 'youtube#subscription',
      etag: 'Da7_Kr-SvEM7k7ym4U2DnhYGjEI',
      id: 'I_5v-i46Mo1ASTbnb0w3KbLKuV8luK4Qu2hHRqoi9q4',
      snippet: [Object],
      contentDetails: [Object]
    },
    {
      kind: 'youtube#subscription',
      etag: '0qvi1ljHGdwce4AbtU5lr7hiV_w',
      id: 'I_5v-i46Mo2B_hsy4IR8bTAgLRZHKJWadXnNDo_9srM',
      snippet: [Object],
      contentDetails: [Object]
    }
  ]
}

【问题讨论】:

  • 您能否在您的页面secured.js 中在if (json.content) { setContent(json.content) } 之前登录console.log(json)
  • 您好,感谢您的回复,它记录:[object Object](仅在浏览器控制台中,没有日志服务器端)
  • console.log(json.content) 怎么样? console.log(typeof json.content) 的类型是什么?
  • 两个日志:未定义
  • 我认为您需要使用console.log(JSON.stringify(json)) 来弄清楚它是什么。

标签: javascript node.js reactjs api next.js


【解决方案1】:

问题在于您的显示逻辑。将有一段时间定义您的会话,并且尚未从后端检索您的内容。

所以应该有类似的东西

  // When rendering client side don't display anything until loading is complete
  if (typeof window !== 'undefined' && loading) return null

  // If no session exists, display access denied message
  if (!session) { return  <Layout><AccessDenied/></Layout> }
  // now retrieving from the backend
  if (!content) { return <div>Retrieving from backend</div> }

【讨论】:

  • 它似乎不起作用,如您所见,注释的逻辑由 next-auth 的示例存储库采用,实际上,如果我不迭代,我所说的内容将返回 json 数据.map
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-30
  • 2020-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多