gpt4 book ai didi

javascript - 将数据从 React 传递到 Node Express 服务器

转载 作者:行者123 更新时间:2023-11-30 14:02:19 24 4
gpt4 key购买 nike

我正在尝试将 generalDetail 数据从我的 react 前端传递到我的 Node 服务器。我目前收到连接被拒绝的错误。

(选项 http://localhost:5000/api/home net::ERR_CONNECTION_REFUSED)。

这是我的 onSubmitForm 函数:

  onSubmitForm(e){
e.preventDefault();

let data = {
generalDetail: this.state.generalDetails,
firstName: this.state.firstName,
middleName: this.state.middleName,
lastName: this.state.lastName
};

axios.post("http://localhost:5000/home", data).then(() => {

}).catch(() => {
console.log("Something went wrong. Plase try again later");
});


}
//end

onContentChange(fieldname, data){

console.log('On Content Change', data);

this.setState({
[fieldname]: data

});
}



}

这是我的 server.js 文件

const express = require('express');

const app = express();


// http://localhost:5000/api/home

app.post('/api/home', (req, res) => {
const data = [
{req.body.generalDetail},
];

res.json(data);
});

const port = 5000;

app.listen(port, () => `Server running on port ${port}`);

最佳答案

你可以把你的代码改成这样

例子

onSubmitForm = e => {
e.preventDefault();
let data = {
generalDetail: this.state.generalDetails,
firstName: this.state.firstName,
middleName: this.state.middleName,
lastName: this.state.lastName
};

axios.post("http://localhost:5000/api/home", data).then(() => {
//do something
}).catch(() => {
console.log("Something went wrong. Plase try again later");
});
}

关于javascript - 将数据从 React 传递到 Node Express 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56122062/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com