使用axios的post请求给出了400错误。 u

问题描述 投票:0回答:1

我知道我的数据库是连接的,因为我的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天时间试图弄清楚我做错了什么。

reactjs post axios mern
1个回答
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);
© www.soinside.com 2019 - 2024. All rights reserved.