React使用axios向Express+MongoDB提交数据报错的解决方法
React+Express跨域提交数据到MongoDB报错解决方案
我的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 Code的Thunder Client扩展测试后端运行正常,可正常执行POST和GET请求操作。以下是相关的后端文件代码供参考:
后端代码参考
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', '*'); // 允许所有域名请求 res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET, POST, PUT, PATCH, DELETE'); // 允许的请求方法 res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization'); // 允许的请求头 next() })
内容的提问来源于stack exchange,提问作者Hakeem
相关产品推荐
相关产品推荐

