【问题标题】:Trouble posting to MongoDB with axios使用 axios 发布到 MongoDB 时遇到问题
【发布时间】:2021-08-17 11:59:11
【问题描述】:

我的 express 服务器在端口 5000 上运行,我的 react 应用程序在端口 3000 上运行。当我尝试向 MongoDB 提交数据时,我不断收到以下错误:

提交时的错误信息:

我认为我的注册表单有问题。首先,我将展示我在 SignUp.jsx 中使用的 状态变量

const SignUp = () => {

const [firstName, setfirstName] = useState('')
   const [lastName, setLastName] = useState('')
   const [email, setEmail] = useState('')
   const [country, setCountry] = useState('')
   const [region, setRegion] = useState('')
   const [wallet, setWallet] = useState('')

   const onChangefirstName = (e) => {
       setfirstName({ firstName: e.target.value })
   }
   const onChangeLastName = (e) => {
       setLastName({ lastName: e.target.value })
   }
   const onChangeEmail = (e) => {
       setEmail({ email: e.target.value})
   }
   const onChangeCountry = (e) => {
       setCountry({ country: e.target.value})
   }
   const onChangeRegion = (e) => {
       setRegion({ region: e.target.value })
   }
   const onChangeWallet = (e) => {
       setWallet({ wallet: e.target.value})
   }

然后,将我的数据发布到 MongoDB 的函数

const onSubmit = (e) => {
   e.preventDefault()
   const newCustomer = {
       firstName: firstName,
       lastName: lastName,
       email: email,
       country: country,
       region: region,
       wallet: wallet
   }

   axios.post('http://localhost:5000/customer/add', newCustomer, {
    headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "GET,HEAD,OPTIONS,POST,PUT"
    },
   })
    .then(res => {
        console.log("status: ", res.status)
        setfirstName('')
        setLastName('')
        setEmail('')
        setCountry('')
        setRegion('')
        setWallet('')
    })
    .catch(err => {console.log(err)})

}

注册表单本身

return (
<div className='grid-container'>
    <header>    
        <h1>Sign Up</h1>          
    </header>  
    <form onSubmit={onSubmit}>
        <label htmlFor="firstName"><b>First Name:</b></label>
        <input type="text" name="firstName" 
        onChange={onChangefirstName} placeholder="Enter first Name"/>

        <label htmlFor="lastName"><b>Last Name:</b></label>
        <input type="text" name="lastName" 
        onChange={onChangeLastName} placeholder="Enter last Name"/>

        <label htmlFor="Email"><b>Email:</b></label>
        <input type="text" name="email" 
        onChange={onChangeEmail} placeholder="Enter Email"/>

        <label htmlFor="country"><b>Select Country:</b></label>
        <input type="list" name="country" 
        onChange={onChangeCountry} id="country"/>
        <datalist id="countries">
            <option value="Bub"></option>
            <option value="Dub"></option>
        </datalist>

        <label htmlFor="region"><b>Select Region</b></label>
        <input list="regions" name="region" 
        onChange={onChangeRegion} id="region"/>
        <datalist id="regions">
            <option value="Bubelbo"></option>
            <option value="Dubelbo"></option>
        </datalist>
        <label htmlFor="wallet"><b>Wallet address</b></label>
        <input type="text" 
        onChange={onChangeWallet} name="wallet"/>

        <div className="submit-container">
            <button type="submit" className="submit-btn">Submit</button>
        </div>
    </form>

</div>
);

当我在 VS 代码中使用迅雷客户端扩展时,后端本身工作正常。我能够毫无问题地发布和获取数据。作为参考,这里是 server.jscustomer.model.jscustomer.route.js 文件:

server.js

const express = require('express')
const mongoose = require('mongoose')
const cors = require('cors')
const app = express()
require('dotenv').config()

app.use(express.json())
app.use(cors({ origin: true }));

const uri = process.env.ATLAS_URI
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true})

mongoose.connection.once('open', () => {
    console.log('mongoDB connected successfully')
})

const customerRouter = require('./routes/customer.crypto')
app.use('/customer', customerRouter)

app.listen(5000, function() {
    console.log('express server is running on port 5000')
})

customer.model.js

const mongoose = require('mongoose')

const CustomerSchema = new mongoose.Schema({
    firstName: {
        type: String,
        required: true,
        trim: true,
    },
    lastName: {
        type: String,
        required: true,
        trim: true,
    },
    email: {
        type: String,
        required: true,
        unique: true,
        trim: true,
    },
    country: {
        type: String,
        required: true,
        trim: true,
    },
    region: {
        type: String,
        required: true,
    },
    wallet: {
        type: String,
        required: true
    }

}, {
    timestamps: true
})

module.exports = mongoose.model('Customer', CustomerSchema)

customer.routes.js

const router = require('express').Router()
let CustomerModel = require('../models/customer.crypto.model')

router.route('/').get((req, res) => {
    CustomerModel.find()
    .then(customers => res.json(customers))
    .catch(err => res.status(400).json(err))
})

router.route('/add').post((req, res) => {
    if(!req.body) {
        return res.status(400).send('Missing req body')
    }
    let newCustomer = new CustomerModel(req.body)

    newCustomer.save()
    .then(() => res.json('Customer added'))
    .catch(err => res.status(400).json(err))
})

module.exports = router

设法找到解决方案,它在 server.js 中添加以下代码,在 app.use(cors())

之后
    app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', '*'); // to enable calls from every domain 
  res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET, POST, PUT, PATCH, DELETE'); // allowed actiosn
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');

【问题讨论】:

    标签: javascript reactjs mongodb axios


    【解决方案1】:

    似乎您在访问 req.body

    之前还没有解析传入的请求正文

    使用https://www.npmjs.com/package/body-parser

    另外,请在开发者工具的 network 选项卡中检查来自 node.js 的响应。

    如果您有任何问题,请告诉我。

    【讨论】:

      【解决方案2】:

      在每个 onChange 处理程序的 SignUp.jsx 文件中,不要传递对象,而是直接传递值 e.target.value

         const onChangefirstName = (e) => {
             setfirstName(e.target.value)
         }
         const onChangeLastName = (e) => {
             setLastName(e.target.value)
         }
         const onChangeEmail = (e) => {
             setEmail(e.target.value)
         }
         const onChangeCountry = (e) => {
             setCountry(e.target.value)
         }
         const onChangeRegion = (e) => {
             setRegion(e.target.value)
         }
         const onChangeWallet = (e) => {
             setWallet(e.target.value)
         }
      

      【讨论】:

        【解决方案3】:

        尝试将代理添加到您的 package.jsonHow to set proxy when using axios to send requests?

        然后将你的 axios 请求更改为axios.post('/customer/add', newCust...

        以前为我工作过。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-02-26
          • 1970-01-01
          • 2013-02-16
          • 1970-01-01
          • 2020-10-01
          • 1970-01-01
          • 2020-02-18
          相关资源
          最近更新 更多