【发布时间】:2019-10-09 23:53:35
【问题描述】:
所以我设置了一个表单来获取用户详细信息并将数据设置为状态。然后我通过 onSubmit 函数将状态数据传递给数据库。我正在使用 axios.post 对本地主机服务器的请求。 我的获取请求似乎工作正常,但是在提交表单后没有发布数据。
我的代码看起来像这样。 (我在抽象不必要的代码。)
UserForm.jsx
class UserForm extends Component {
constructor(props) {
super(props);
this.state = {
name: "",
contact: "",
company: "",
mail: "",
key: {
wedding: false,
MICE: false,
corporate: false
},
app_no: "",
items: "",
isLoaded: false
};
}
handleSubmit = e => {
console.log("Submitted");
e.preventDefault();
const users = {
name: this.state.name,
contact: this.state.contact,
company: this.state.company,
mail: this.state.mail,
key: this.state.key,
app_no: this.state.app_no
};
axios
.post(
"http://localhost:5000/api/items",
{ users },
{
headers: {
"content-type": "application/json"
}
}
)
.then(console.log("Axios post is working"))
.then(res => {
console.log("Something: " + res);
console.log(res.data);
})
.catch(err => {
console.log(err);
});
console.log("Users; " + users.name);
};
componentDidMount() {
fetch("http://localhost:5000/api/items/", {
headers: {
"content-type": "application/json"
}
})
.then(res => res.json())
.then(json => {
this.setState({
isLoaded: true,
items: json
});
});
console.log(this.state.items);
}
我的表单似乎工作正常,并在控制台上提供了所有项目。 这是我的 items.js 文件:
const express = require("express");
const router = express.Router();
// Item model
const Item = require("../../models/Item");
// Routes
// @get API item get all items
// make a get req
router.get("/", (req, res) => {
Item.find().then(items => res.json(items));
});
// @get Api item POST all items
// make a post req
// create an item
router.post("/", (req, res) => {
const newItem = new Item({
name: req.body.name,
contact_no: req.body.contact_no,
company_name: req.body.company_name,
key: req.body.key
});
newItem.save().then(item => res.json(item));
});
// @del api item.
// delete request
router.delete("/:id", (req, res) => {
Item.findById(req.params.id)
.then(item => item.remove().then(() => res.json({ success: true })))
.catch(err => res.status(404).json({ success: false }));
});
module.exports = router;
我在代码中遗漏了什么。我浏览了大部分 axios 文档,似乎找不到问题。
server.js
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const app = express();
const items = require("./routes/api/items"); // Contains all the api routes
// Body Parser middleware
app.use(bodyParser.json());
// DB config
const db = require("./config/keys").mongoURI;
mongoose
.connect(db, { useNewUrlParser: true })
.then(() => console.log("Mongo is laoded"))
.catch(err => console.log(err));
app.use("/api/items", items); // redirecting api routes to items
const port = process.env.PORT || 5000;
app.listen(port, () => console.log("Server started"));
如果我应该发布更多代码,请告诉我.. 编辑:我没有得到 "console.log("Something: " + res); console.log(res.data);" 控制台上的响应。 我的控制台打印:
(2) [{…}, {…}]
Submitted
UserForm.jsx:56 Axios post is working
UserForm.jsx:70 Users; someuser
【问题讨论】:
-
我想我没有收到 res 的回复