javascript - Axios PUT 请求未将所有数据发送到服务器 JS
问题描述
我正在使用 ReactJs、MongoDB 和 Express 编写我的第一个应用程序。我的问题是我正在发送带有某些数据的 axios 请求,但是,并非所有数据都在用户模型中更新。请在下面查看我的代码:
带 axios 请求的前端代码:
import axios from "axios"
import { useState } from "react"
import { useDispatch, useSelector } from "react-redux"
import { changeAddress, changeError, changeNatId, changePhone } from "../../store/contactReducer"
import { NavBar } from "../Navbar"
export const ContactInfoForm = function({nombre, correo, userId, cedula, telefono, direccion}) {
const { natId, address, phone, error } = useSelector(({contactReducer}) => ({
nationalid: contactReducer.nationalid,
address: contactReducer.address,
phone: contactReducer.phone,
error: contactReducer.error,
}))
const [edit, setEdit] = useState(false)
const dispatch = useDispatch()
async function handleSubmit(e) {
e.preventDefault()
try {
const { data } = await axios({
method: 'PUT',
baseURL: process.env.REACT_APP_SERVER_URL,
url: `/users/user/${userId}`,
data: {
nationalid: natId,
address: address,
phone: phone,
}
})
console.log(data)
}catch(error) {
dispatch(changeError(error))
}
}
if(edit === true) {
return(
<>
<NavBar />
<form onSubmit={handleSubmit}>
<label htmlFor='nombre'>Nombre</label>
<p
id='nombre'
>
{nombre}
</p>
<label htmlFor='correo'>Correo</label>
<p
id='correo'
>
{correo}
</p>
<label htmlFor='cedula'>Cédula</label>
<input
type='text'
id='cedula'
onChange={e => dispatch(changeNatId(e.target.value))}
/>
<label htmlFor='direccion'>Dirección</label>
<input
type='text'
id='direccion'
onChange={e => dispatch(changeAddress(e.target.value))}
/>
<label htmlFor='telefono'>Teléfono</label>
<input
type='text'
id='telefono'
onChange={e => dispatch(changePhone(e.target.value))}
/>
<button
type='submit'
onClickC={handleSubmit}
>
Guardar Información
</button>
</form>
<button
type='button'
onClick={(e) => setEdit(false)}
>
Cancelar
</button>
</>
)
}else if(edit === false) {
return(
<>
<NavBar />
<form>
<label htmlFor='nombre'>Nombre</label>
<p
id='nombre'
>
{nombre}
</p>
<label htmlFor='correo'>Correo</label>
<p
id='correo'
>
{correo}
</p>
<label htmlFor='cedula'>Cédula</label>
<p
id='cedula'
>
{cedula}
</p>
<label htmlFor='direccion'>Dirección</label>
<p
id='direccion'
>
{direccion}
</p>
<label htmlFor='telefono'>Teléfono</label>
<p
id='telefono'
>
{telefono}
</p>
</form>
<button
type='button'
onClick={() => setEdit(true)}
>
Editar
</button>
</>
)
}
}
后端的用户模型:
const { model, models, Schema } = require('mongoose')
const bcrypt = require('bcrypt')
const userSchema = new Schema({
email: {
type: String,
required: true,
validate: {
async validator(email) {
try {
const user = await models.User.findOne({ email })
return !user
} catch(error){
return false
}
},
message: 'El correo ya está en uso'
},
},
password: {
type: String,
required: true,
},
address: {
type: String,
},
phone: {
type: String,
},
products: {
type: [{
type: Schema.Types.ObjectId,
ref: 'Product'
}]
},
name: {
type: String,
required: true,
},
nationalid: {
type: String,
unique: true,
},
transactions: {
type: [{
type: Schema.Types.ObjectId,
ref: 'Transaction',
}]
},
})
userSchema.pre('save', async function() {
if(this.password && this.isModified('password')) {
this.password = await bcrypt.hash(this.password, 8)
}
})
const User = model('User', userSchema)
module.exports = User
在后端更新控制器:
async update(req, res) {
try {
const {body, params: {userId}} = req
const user = await User.findByIdAndUpdate(userId, body, {new:true}).select('-password')
await user.save({ validateBeforeSave: false })
res.status(201).json(user)
console.log(user)
}catch(error) {
res.status(400).json(`No se puede actualizar el usuario ${error}`)
console.log(error)
}
},
Address
并且phone number
正在正确更新,但是,nationalid
在我的一生中不会更新。请记住,这是我第一次编写应用程序,因此您可能会在我的代码中遇到缺陷。
解决方案
我在代码中发现了错误,我忘记将前端文件中的第 8 行从const { natId, address, phone, error }
更改为const { nationalid, address, phone, error }
以匹配后端模型中的名称。
推荐阅读
- unity3d - 在 Start 中调用的 Time.time 的值是否总是等于在第一次调用 Update 时调用的值?
- r - 如何在ggplot2中使用线/块分隔制作连续图
- amazon-web-services - AWS SSM RunCommand - Issue with RunRemoteScript Document to run PowerShell script with parameters
- docker - 如何禁用为公共访问添加到 iptables 的所有 docker 规则?
- c# - CanStop = false, but I can't start the service
- html - Create multiple tables based on json data in Angular 8
- r - 如何在R中将两列合并为一列?
- c++ - How to kill/signal other child processes from another child process?
- python - 在 for 循环中调用和演化函数
- reactjs - Error with Next Js with Expo when compiling