【问题标题】:Why is react not posting res.json() to console?为什么反应不发布 res.json() 到控制台?
【发布时间】:2022-01-15 23:22:27
【问题描述】:

我已经尝试了很多东西,但我的反应应用程序没有收到 jsonData 变量或 res 作为节点应用程序的返回。该应用程序正在运行并打印到节点端的控制台,但我无法让它打印到反应端。

  const submitForm = async (event) => {
    event.preventDefault(); // Prevent default submission
    const data2 = document.getElementById("miles").value;
    const data =
      "passenger_vehicle-vehicle_type_" +
      carType +
      "-fuel_source_" +
      vehicleType +
      "-engine_size_na-vehicle_age_na-vehicle_weight_na";
    axios
      .post(`http://localhost:8000/api/vehicle/`, { data, data2 })
      .then((res) => {
        const returnText = res.json();
        console.log(returnText);
        return res.json();
      })
      .then((jsonData) => {
        console.log(jsonData);
        return;
      })
      .catch((error) => {
        console.log("got errr while posting data", error);
      });
  };

我把 api 和 api key 都删掉了。

var fetch = require('node-fetch');

exports.vehicle = (req, res) =>{
let status; 
const { data, data2 } = res.body;
const values = {
  "emission_factor": data,
  "parameters": {
    "distance": parseInt(data2),
    "distance_unit": "mi",
  },
};

fetch('https://AAAAAAAAAAAAAAAA', {
    method: 'POST',
    headers: {
        'Authorization': 'Bearer MYAPIKEY',
        'Content-Type': 'application/json'
    },
    body: JSON.stringify(values)
})
  .then((res) => { 
    status = res.status;
    return res.json()
  })
  .then((jsonData) => {
    console.log(jsonData);
    console.log(status);
    return jsonData
  })
  .catch((err) => {
    // handle error
    console.error(err);
  });
res.send(req.body);
}

工作代码感谢您的帮助:

const submitForm = async (event) => {
    event.preventDefault(); // Prevent default submission
    const data2 = document.getElementById("miles").value;
    const data =
      "passenger_vehicle-vehicle_type_" +
      carType +
      "-fuel_source_" +
      vehicleType +
      "-engine_size_na-vehicle_age_na-vehicle_weight_na";
    axios
      .post(`http://localhost:8000/api/vehicle/`, { data, data2 })
      .then((res) => {
        console.log(res.data);
        return;
      })
      .catch((error) => {
        console.log("got err while posting data", error);
      });
  };

cmets 中的节点解决方案。

【问题讨论】:

  • 你有几个很好的回复。如果您觉得它们有帮助,请“点赞”和“接受”。另外:您究竟在哪里寻找 console.log()console.error() 消息。我希望您正在查看 Chrome 开发工具(或等效工具)中的 [控制台] 选项卡。我希望你不认为它们显示在命令提示符窗口中:(

标签: node.js reactjs axios fetch-api


【解决方案1】:

这里有两个问题...

  1. 客户端,您似乎将Axios responsefetch() Response 混淆了。你想要res.data不是 res.json()。由于您已使用 标记此内容,因此您可以在此处将数据设置为状态值,例如

    axios.post(...).then(res => {
      setSomeState(res.data)
    })
    
  2. 服务器端,您无需等待获取请求完成。我建议使用async 函数

    exports.vehicle = async (req, res) => {
      try {
        const { data, data2 } = req.body
    
        const values = {
          "emission_factor": data,
          "parameters": {
            "distance": parseInt(data2),
            "distance_unit": "mi",
          },
        }
    
        // don't mix up the Express "res" with the fetch "response"
        const response = await fetch('https://AAAAAAAAAAAAAAAA', {
          method: 'POST',
          headers: {
            'Authorization': 'Bearer MYAPIKEY',
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(values)
        })
    
        if (!response.ok) {
          throw new Error(`${response.status}: ${await response.text()}`)
        }
    
        res.json(await response.json()) // respond with the data
      } catch (err) {
        console.error(err)
        res.status(500).send(err)
      }
    }
    

【讨论】:

  • 如果这个答案有问题,我很想知道它是什么,所以我可以解决它
  • 我认为它是 req.body 但就是这样。现在一切正常,感谢您的帮助。
  • @joe欢呼,复制/粘贴错误
【解决方案2】:

then() 语句中的函数需要返回数据,例如then((res) => {return res.json()})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-01
    相关资源
    最近更新 更多