带有axios的发布请求给出错误400。u

时间:2020-05-05 21:05:54

标签: reactjs post axios mern

所以我刚开始构建应用程序并且一直在构建提交表单,但是我的发布请求给我一个错误400。我知道我的数据库已连接,因为我的GET请求工作正常,并且我知道我的API在某种程度上可以正常工作,因为失眠POST请求正常吗?这是我的apply.js页面的代码。在控制台中,状态变化显示出来,所以我认为信息传递得很好。我觉得这一定是我的发帖要求不好的地方。

function Apply() {
    const [applicant, setApplicant] = useState("");
    const [address, setAddress] = useState("");
    const [loanAmount, setLoanAmount] = useState(0);

  const handleChange = ({target})=> {
    if(target.name === "username") setApplicant(target.value);
    else if(target.name === "address") setAddress(target.value);
    else if(target.name === "loanAmount") setLoanAmount(target.value);
    else console.error("error changing Applicant");
  }
  const handleSubmit = (e) => {
    e.preventDefault() 
    console.log(applicant, loanAmount, address);

    axios
    .post('http://localhost:5000/users/add',{applicant, loanAmount, address}) 
    .then(res => console.log(res.data))
    .catch(err => console.log("Error of type: " + err))

我觉得我在做一些愚蠢的事情,或者只是在语法上很愚蠢,但这是user.model,js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
    username: { type: String, required: true, unique: true, trim: true, minlength: 3},
    loanrequest: {type: Number, required: true, trim: true},
    address: {type: String, required: true, trim: true },
    email: {type: String, required: false, trim: true}
});

let users = mongoose.model('User', userSchema);

module.exports = users;

这是我的路线,它使用的是Users.js中的模型

const router = require('express').Router();
let User = require('../models/user.model');

router.get('/', (req,res) => {
    User.find(req.params.id)
    .then(users => res.json(users))
    .catch(err => res.status(400).json('Error: ' + err));
});

router.post('/add', (req, res) => {

    const username= req.body.username;
    const loanrequest= Number(req.body.loanrequest);
    const address= req.body.address;
    const email = req.body.address;
    const newUser = new User ({
        username,
        loanrequest,
        address,
        email
     });

        newUser.save()
        .then(() => res.json('Application Added!'))
        .catch(err => res.status(400).json('Error: ' + err));
    });

module.exports = router;

很抱歉,如果这篇文章超长。我花了大约2天的时间试图弄清楚我做错了什么。感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您尝试使用此代码代替

const username= req.body.username;
const loanrequest= Number(req.body.loanrequest);
const address= req.body.address;
const email = req.body.address;
const newUser = new User({
    username,
    loanrequest,
    address,
    email
 });

下面的代码,我认为您无法创建这样的新文档,因为在上述情况下,该架构将采用如下对象:{1:...,2:...},而不是所需的对象属性(用户名,电子邮件等)

const userData = {
    username: req.body.username,
    loanrequest: Number(req.body.loanrequest),
    address: req.body.address,
    email: req.body.address
}
const newUser = new User(userData);