【问题标题】:Is there something missing in this code ? I am unable to post through axios post request此代码中是否缺少某些内容?我无法通过 axios 发帖请求发帖
【发布时间】: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 的回复

标签: reactjs axios mern


【解决方案1】:

我不相信您能够通过req.body.name 获取您的记录,因为您的 POST 请求似乎将其置于req.body.users.name 之下,所以基本上您希望从@987654323 获取您的数据@

【讨论】:

  • 所以我应该用req.body.user 替换req.body.users.name
  • 不确定我理解你的意思。
  • 我的意思是,如果我要建议要改变的东西,可能有很多,但是关于你的问题,如果你替换它,但你还需要更新如何您正在将用户数据从前端传递到后端。如果你继续你所拥有的,我想说的是你需要通过req.body.users 而不是后端的req.body 访问用户数据。所以从技术上讲,你可以只拥有const newItem = new Item(req.body.users)
【解决方案2】:

也许是因为你的第二个 .then 在 axios.post 将所有内容放在一个 .then

试试这个:

.then((res) => {
console.log("Axios post is working")
console.log("Something: " + res);
console.log(res.data);
})

【讨论】:

  • 加上响应不会打印在控制台上。
  • @ArjunKashyap 你在关注 MERN youtube 系列吗?您是否尝试过使用邮递员发帖?检查您的反应是什么。还要检查 chrome 开发人员工具以检查网络选项卡中发生的情况,您可以在那里查看响应
  • 是的,我最初关注它。我尝试通过帖子管理员发布请求。它失败了。 Could not get any response There was an error connecting to http://localhost:5000/api/items.
  • 你可以使用get方法吗?很外行。请提供有关您在尝试使用方法 post、在您的服务器 js 和 chrome 开发人员工具网络选项卡中获得的信息
猜你喜欢
  • 2023-03-27
  • 1970-01-01
  • 2015-03-02
  • 2018-03-24
  • 2019-11-20
  • 1970-01-01
  • 2017-04-11
  • 1970-01-01
  • 2018-10-03
相关资源
最近更新 更多