利用nextjs前端从strapi中获取axios方法

nxagd54h  于 2022-11-05  发布在  iOS
关注(0)|答案(1)|浏览(166)
import axios from "axios";
import Head from "next/head";
import * as React from "react";
import * as Material from "@mui/material";
import IconButton from '@mui/material/IconButton';
import Badge from '@mui/material/Badge';
import MailIcon from '@mui/icons-material/Mail';
//import Container from "@mui/material";
import styles from "../styles/Home.module.css";
import { Container } from "@mui/material";

function notificationsLabel(count) {
  if (count === 0) {
    return 'no notifications';
  }
  if (count > 99) {
    return 'more than 99 notifications';
  }
  return `${count} notifications`;
}

export default function Home({ pages }) {
  return (
    <div className={styles.container}>

      <Head>
        <title>Create Next App</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>

          <h1>{pages[0].Title}</h1>
          <h2>{pages[0].Description}</h2>

    </div>

  );
}

export async function getServerSideProps() {

  const postRes = await axios.get("http://localhost:1337/api/pages");

  return {

    props: {

      pages: postRes.data
    },

  };
}`

我正在使用strapi和nextjs我是以下一些视频工作,在我看来,视频是有点老,也许,但它没有工作的预期。youtube link所以谁能建议检索过程中的数据与Axios获取从strapi?

es\react-dom\cjs\react-dom-server.browser.development.js:6076:14) {

第页:'/' } 34|三十五个|
三十六人|

{第[0]页.标题}

| 三十七年|

{第[0]页.说明}

三十八|三十九|

cqoc49vn

cqoc49vn1#

最有可能的解决方案

import axios from "axios";
import Head from "next/head";
//import * as React from "react";
//import * as Material from "@mui/material";
import IconButton from '@mui/material/IconButton';
import Badge from '@mui/material/Badge';
import MailIcon from '@mui/icons-material/Mail';
//import Container from "@mui/material";
import style from "../styles/Home.module.css";
import { Container } from "@mui/material";
import { useState, useEffect } from "react";
//import { style } from "@mui/system";

//function notificationsLabel(count) {
//if (count === 0) {
//return 'no notifications';
//}
//if (count > 99) {
//return 'more than 99 notifications';
//}
//return `${count} notifications`;
//}

/*
export default function Home({ pages }) {
  return (
    <div className={styles.container}>

      // <Head>
      //  <title>Create Next App</title>
      //  <link rel="icon" href="/favicon.ico" />
     // </Head>

      {pages &&
        pages.map(pages => (

          <Container key={pages.id}>
            <h2>{pages.Title}</h2>

          </Container>
        ))};
    </div>

  );
}

export async function getServerSideProps() {
  const [posts, setPosts] = useState([]);
  const apiEndPoint = "http://localhost:1337/api/pages";
  // const postRes = await axios.get("http://localhost:1337/api/pages");
  //const pages = await postRes.request();
  axios.get(apiEndPoint).then(response => {
    console.log(response.data);
  });

  return {

    props: {

      pages: response
    },

  };
}

* /

const Home = ({ Pages, error }) => {
  if (error) {
    return <div classname={style.Container} >An error occured: {error.message}</div>;
  }
  return (
    <div className={style.main}>
      <Head>
        <title>Create Next App</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <main className={style.main}>
        <h1 className={style.title}>
          Welcome to <a href="https://nextjs.org">
            Next.js!</a> integrated with{" "}
          <a href="https://mui.com/">Material-UI!</a>
        </h1>
        <p className={style.description}>
          Get started by editing{" "}
          <code className={style.code}>
            pages/index.js</code>
        </p>

      </main>

      <div classname={style.card} >
        {Pages.data.map(Pages => (
          <div classname={style.main}>{Pages.attributes.Title}</div>
        ))} </div>
    </div>
  );
};

Home.getInitialProps = async ctx => {
  try {
    const res = await axios.get('http://localhost:1337/api/pages');
    const Pages = res.data;
    return { Pages };
  } catch (error) {
    return { error };
  }
};

export default Home;

要了解更多,请查看nextjs doc。现在看起来更有希望。

import axios from "axios";
import Head from "next/head";
import * as React from "react";
//import * as Material from "@mui/material";
import IconButton from '@mui/material/IconButton';
import Badge from '@mui/material/Badge';
import MailIcon from '@mui/icons-material/Mail';
//import Container from "@mui/material";
import style from "../styles/Home.module.css";
import Typography from '@mui/material/Typography';
import CardContent from '@mui/material/CardContent';
import Card from '@mui/material/Card';
import CardHeader from '@mui/material/CardHeader';
import CardMedia from '@mui/material/CardMedia';
import { red } from '@mui/material/colors';
import MoreVertIcon from '@mui/icons-material/MoreVert';
import FavoriteIcon from '@mui/icons-material/Favorite';
import ShareIcon from '@mui/icons-material/Share';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import { styled } from '@mui/material/styles';
import CardActions from '@mui/material/CardActions';
import Collapse from '@mui/material/Collapse';
import Rating from '@mui/material/Rating';
import Avatar from '@mui/material/Avatar';
import Stack from '@mui/material/Stack';
import Toolbar from '@mui/material/Toolbar';
import Box from '@mui/material/Box';
import { Container } from "@mui/material";
import { useState, useEffect } from "react";

//import { style } from "@mui/system";

//function notificationsLabel(count) {
//if (count === 0) {
//return 'no notifications';
//}
//if (count > 99) {
//return 'more than 99 notifications';
//}
//return `${count} notifications`;
//}

/*
export default function Home({ pages }) {
  return (
    <div className={styles.container}>

      // <Head>
      //  <title>Create Next App</title>
      //  <link rel="icon" href="/favicon.ico" />
     // </Head>

      {pages &&
        pages.map(pages => (

          <Container key={pages.id}>
            <h2>{pages.Title}</h2>

          </Container>
        ))};
    </div>

  );
}

export async function getServerSideProps() {
  //const [posts, setPosts] = useState([]);
  const apiEndPoint = "http://localhost:1337/api/pages";
  const postRes = await axios.get("http://localhost:1337/api/pages");
  //const pages = await postRes.request();
  //axios.get(apiEndPoint).then(response => {
  //console.log(response.attributes);
  //});

  return {

    props: {

      pages: postRes.json().then((postres.attributes) => ({ postres.attributes })),
    },

  };
}

* /

const ExpandMore = styled((props) => {
  const { expand, ...other } = props;
  return <IconButton {...other} />;
})(({ theme, expand }) => ({
  transform: !expand ? 'rotate(0deg)' : 'rotate(180deg)',
  marginLeft: 'auto',
  transition: theme.transitions.create('transform', {
    duration: theme.transitions.duration.shortest,
  }),
}));

const Home = ({ Pages, error }) => {
  const [expanded, setExpanded] = React.useState(false);

  const handleExpandClick = () => {
    setExpanded(!expanded);
  };

  if (error) {
    return <div classname={style.Container} >An error occured: {error.message}</div>;
  }
  return (
    <div className={style.main}>

      <Toolbar>
        {Pages.data.map(Pages => (
          //<div classname={style.main}>
          <Card sx={{ flexDirection: 'row', maxWidth: 545, borderRadius: "20px", spacing: "125px", boxShadow: "7px", alignItems: 'stretch' }} elevation={4} position="relative">
              <CardHeader
                avatar={
                  <Avatar sx={{ bgcolor: red[200], spacing: "5px" , margin:"2px" }} aria-label="Technocrat">
                    TC
                  </Avatar>
                }
                action={
                  <IconButton aria-label="settings">
                    <MoreVertIcon />
                  </IconButton>
                }
                title={Pages.attributes.Title}
                subheader="September 14, 2016"
              />
              <CardMedia
                component="img"
                height="200"
                image="{Pages.attributes.Images}"
                alt="Paella dish"
              />
              <CardContent>

                <Typography variant="body2" color="text.secondary">
                  {Pages.attributes.Description}</Typography>
              </CardContent>
              <CardActions enableSpacing>
                <IconButton aria-label="add to favorites">
                  <FavoriteIcon />
                  <Rating name="half-rating" defaultValue={2.5} precision={0.5} />
                </IconButton>
                <IconButton aria-label="share">
                  <ShareIcon />
                </IconButton>
                <ExpandMore
                  expand={expanded}
                  onClick={handleExpandClick}
                  aria-expanded={expanded}
                  aria-label="show more"
                >
                  <ExpandMoreIcon />
                </ExpandMore>
              </CardActions>
              <Collapse in={expanded} timeout="auto" unmountOnExit>

                <Typography paragraph padding="10px">

                  <Box sx={{ my: 8 , spacing: 10, margin:2 }}>  {Pages.attributes.Content} </Box></Typography>
              </Collapse>
            </Card>
    //      </div>

        ))} </Toolbar>
    </div>
  );
};

Home.getInitialProps = async ctx => {
  try {

    const res = await axios.get('http://localhost:1337/api/' + 'pages');
    const Pages = res.data;
    return { Pages };
  } catch (error) {
    return { error };
  }
};

export default Home;

所以它可以{<API>.attributes.<Field>}这样的方式被访问{pages.attributes.Title}

相关问题