【问题标题】:How to post values from reactjs to expressJs如何将值从 reactjs 发布到 expressJs
【发布时间】:2020-12-27 16:18:10
【问题描述】:

我的前端代码:-

const [stocks, setStocks] = useState([

    {
        "name": "TSLA"
    },
    {
        "name": "AAPL"
    },
    {
        "name": "AMZN"
    }
])


useEffect(() => {
    fetch('http://localhost:2701/' , {
        method: "POST",
        headers: {
            'Content-type': 'application/json'
        },
        body: JSON.stringify(stocks)
        })
        .then((result) => {
            console.log(result)
        })
        .then((info) => { console.log(info); })
})

我的后端代码:-

router.post('/', async (req, res) => {
    var data = req.body.data;
    console.log("Data:-", data)
})

我想将值从 reactjs 发送到 nodejs 服务器,如果可能的话,任何人都可以建议使用 axios

【问题讨论】:

  • 但是问题是什么?你有什么错误吗?
  • 我得到未定义的值
  • 你有没有解析body的中间件?是客户端发出了错误的请求,还是服务器错误地处理了它?找出并给相应方的minimal reproducible example
  • 你使用的是body-parser还是JSON parser?
  • 这能回答你的问题吗? Fetch: POST json data

标签: node.js reactjs mern


【解决方案1】:

请尝试下面的代码。

import axios from 'Axios';
...
    axios.post('http://localhost:2701/').then(response => {
      console.log(response);
    });

【讨论】:

  • 你认为这会解决什么问题?
  • 这给了他一个sn-p代码来使用axios。
  • 但这修复是什么?您是否想说 fetch 不能做他们想做的事(它可以)?这甚至不是正确使用 axios 来发布数据,因为您没有包含任何数据。
  • OP 正在使用fetch API,为什么建议使用不同的包?
猜你喜欢
  • 2018-05-17
  • 2020-12-17
  • 2022-12-15
  • 2019-05-14
  • 2018-06-19
  • 2017-01-07
  • 2016-11-22
  • 2020-10-09
  • 1970-01-01
相关资源
最近更新 更多