You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js中useEffect调用API时ServerSideProps传递的email始终为undefined

解决ServerSideProps传递email后API接收undefined的问题

核心问题分析

你的代码存在两个关键错误,直接导致API接收到的email为undefined:

1. Axios GET请求参数传递方式错误

在组件的useEffect中,你直接将email作为axios.get的第二个参数传入,但axios的GET请求第二个参数是配置对象,查询参数必须放在params字段内。当前写法会把email作为配置属性而非请求参数,后端无法读取到该值。

2. map函数无返回值

wishlistProducts.map内部没有返回<label>元素,这会导致页面无法渲染心愿单内容,虽不影响email传递,但属于必须修复的渲染问题。

另外,getServerSideProps中调用/api/users/wishlist时未传递email,这部分返回的wishlist数据也会是错误的,建议一并修正。

修复后的完整代码

import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import axios from 'axios';
import { useSession } from 'next-auth/react';
import { QUERIES_SHOE, WEIGHTS_SHOE } from '../constants';

const Wishlist = ({ products, email, wishlist }) => {
    const { data: session, status } = useSession()
    const [wishlistProducts, setWishlistProducts] = useState([]);

    useEffect(() => {
      if(!email) return;
      
      const fetchWishlist = async() => {
        // 修正:将email放入params作为URL查询参数
        const ress = await axios.get(buildUrl('/api/users/wishlist'), {
          params: { email }
        });
        const data = ress.rows?.[0];
        setWishlistProducts(data || []); // 加默认值避免map报错
      };
      fetchWishlist();
    }, [email]);

    console.log('wish', wishlist)

  return (
    <Wrapper>
      {wishlistProducts.length > 0 ?
        <>
          {wishlistProducts.map((wish, index) => {
            // 修正:添加return和key属性
            return <label key={index}>{wish}</label>
          })}
        </>
      : <p>暂无心愿单内容</p>
      }
    </Wrapper>
  );
};

export const getServerSideProps = async (context) => {
    const res = await axios.get(buildUrl('/api/products'))
    const session = await getSession({ req: context.req });
    if (!session) {
      return {
        redirect: {
          destination: '/login',
          permanent: false,
        }
      };
    }
    const email = session?.user?.user?.email;
    console.log(email)
    // 修正:调用心愿单API时传递email参数
    const ress = await axios.get(buildUrl('/api/users/wishlist'), {
      params: { email }
    });
    return {
        props: {
            products: res.data,
            wishlist: ress.data,
            email,
        }
    }
}

export default Wishlist;

额外注意事项

  • 确认后端API是从URL查询参数中获取email(比如Express框架用req.query.email),如果后端期望从请求体获取,需将GET请求改为POST,并在axios中用data字段传递email。
  • 检查session?.user?.user?.email的层级是否正确,通过getServerSideProps中的console.log确认email本身是否存在,避免因session结构错误导致初始值为undefined。

内容的提问来源于stack exchange,提问作者NroGamerz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 05:20:50