亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么我的 axios 帖子在我的功能組件中返回未定義?

為什么我的 axios 帖子在我的功能組件中返回未定義?

aluckdog 2022-08-04 17:54:02
我是Next Js和函數式共生體的新手。我正在嘗試從 /api/retrieve2 檢索數據//this is retrieve pageexport default function Retrieve() {    const onSubmit = async data => {                const { user } = await axios.post("/api/retrieve2", data);        console.log(user) // user here is undefined        };    return (...);}//this is retrieve2, inside the API folderexport default async (req, res) => {    try {        const { data } = await axios.post(myBackendUrl, req.body);        console.log(data) //this is printing the right data - { email: '[email protected]', code: '123123' }        res.json(data);    } catch (e) {        res.json({ err: e.message || e });    }};我錯過了什么,這是關于下一步的東西嗎?關于功能組件?
查看完整描述

2 回答

?
小唯快跑啊

TA貢獻1863條經驗 獲得超2個贊

您應該閱讀有關 ES6 的信息destructuring

你試圖去結構,但公理回應女巫是一個對象不包含鑰匙useruser

因為它有效,因為響應中有一個數據屬性data

以下是可以取消結構的所有屬性:

{ data, status, statusText, headers, config, request }


查看完整回答
反對 回復 2022-08-04
?
犯罪嫌疑人X

TA貢獻2080條經驗 獲得超4個贊

您需要獲取完整的URL才能使用getInitialProps發出http請求,這里的Home是您的組件的名稱


const Home = ({ENDPOINT}) => {

   const onSubmit = async data => {        

        const { data } = await axios.post(`${ENDPOINT}/api/retrieve2`, data);

        // consider changing `user` here to `data` since Axios stores response in data object 

        console.log(data) // should be defined

   };


   return (...);


}


Home.getInitialProps = ctx => {

  const ENDPOINT = getEndpoint(ctx.req);

  return { ENDPOINT };

};


// You should store this somewhere you can reuse it

export function getEndpoint(req) {

  return !!req

    ? `${req.headers['x-forwarded-proto']}://${req.headers['x-forwarded-host']}`

    : window.location.origin;

}


查看完整回答
反對 回復 2022-08-04
  • 2 回答
  • 0 關注
  • 129 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號