我正在尝试将通用详细信息数据从我的反应前端传递到我的节点服务器。我目前收到连接被拒绝的错误。
(选项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}`);
答案 0 :(得分:1)
尝试
const express = require('express')
const app = express()
const port = 8000 //your port number
const cors = require('cors')
app.use(cors())
var bodyParser = require('body-parser')
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
答案 1 :(得分:1)
您可以将代码更改为此
示例
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");
});
}
答案 2 :(得分:0)
尝试在后端代码(server.js)中添加cors预检代码。
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", req.headers.origin);
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
res.header("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS");
res.header("Access-Control-Allow-Credentials", true);
next();
});
app.post('/api/home', (req, res) => {
const data = [{ generalDetails: req.body.generalDetail }];
res.json(data);
});