【问题标题】:How do I send response object from my get request to the front end with Express and Axios?如何使用 Express 和 Axios 从我的 get 请求发送响应对象到前端?
【发布时间】:2021-08-13 05:38:52
【问题描述】:

我正在尝试从 MongoDB 中提取数据以填充我正在构建的这个应用程序中的一些计时器。但是,我似乎无法使用 Axios 将我的响应发送到前端。这是我在后端的路线:

const express = require('express');
const router = express.Router();

const TimerModel = require('../models/Timer');

router.get('/', async (req, res) => {
  try {
    const timers = await TimerModel.find({});
    console.log('Succesful get req', timers);
    res.send(timers);
  } catch (err) {
    console.log(err.message);
    res.status(500).send('Server Error');
  }
});

module.exports = router;

我在 try 语句中的 console.log 打印了正确的数据,但我在将其发送到前端时遇到了问题。这是组件:

import React, { useState, useEffect } from 'react';
import Timer from '../Timer/Timer';
import axios from 'axios';

import './Wrapper.css';

function Wrapper() {

  //State effects

  useEffect(() => {
    axios
      .get('/')
      .then((res) => {
        console.log(res);
        console.log(res.data);
      })
      .catch((err) => {
        console.log(err);
      });
  });
  const handleChange = (event) => {
    setTitle(event.target.value);
  };

  const addTimer = () => {
    const timer = <Timer title={title}     key={timers.length} />;
    let allTimers = timers.slice();
    allTimers.push(timer);
    setTimers(allTimers);
    setTitle('');
  };

  return (
  
  //JSX Code
  
  );
}

export default Wrapper;
在我进行的axios 调用中,当我运行console.log(res) 时,我得到了这个奇怪的对象,而res.data 得到了我的index.html。为什么我无法访问通过后端请求创建的计时器对象?当我在我的路线中运行命令res.send(timers) 时,它不会被发送吗?

【问题讨论】:

    标签: express mongoose routes axios mern


    【解决方案1】:

    您需要在 axios 请求中添加您的 API url。目前,axios 正在获取您的 React 网站的 url,这就是为什么您的响应包含 React 网站的 index.html 文件。

    useEffect(() => {
    axios
      .get('api_url/')
      .then((res) => {
        console.log(res);
        console.log(res.data);
      })
      .catch((err) => {
        console.log(err);
      });
    
    });
    

    【讨论】:

      【解决方案2】:

      您可以将结果保存为类似的状态

      `````````````
      `````````````
      const [time, setTimer] = useState(null)
      useEffect(() => {
      axios.get('/').then(res => setTimer(res.data)
      }, [])
      `````````````
      `````````````
      

      然后在你想要的地方使用时间变量

      【讨论】:

        猜你喜欢
        • 2020-06-27
        • 1970-01-01
        • 2018-11-02
        • 1970-01-01
        • 1970-01-01
        • 2023-04-11
        • 2018-03-11
        • 2021-08-01
        • 1970-01-01
        相关资源
        最近更新 更多