在这里,我试图通过POST
使用axios
向MongoDB插入一个对象.我发送的对象成功地插入到MongoDB集合中.在插入对象后,我需要重定向到主页,但我在axios
response
data
内收到axios
错误request failed with status code 500
,并给出消息No write concern mode named majority found in replica set configuration
以下是我的代码
UserSignUp.jsx
个
export default function SignUpScreen() {
const navigate = useNavigate();
const { search } = useLocation();
const redirectInUrl = new URLSearchParams(search).get('redirect');
const redirect = redirectInUrl ? redirectInUrl : '/';
const [name,setName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('')
const { state, dispatch: ctxDispatch } = useContext(Store);
const { userInfo } = state;
const submitHandler = async e => {
e.preventDefault();
if(password !== confirmPassword) {
toast.error('Passwords do not match');
return;
}
try {
const { data } = await axios.post('/api/users/signup', {
name,
email,
password,
});
ctxDispatch({ type: 'User_SignIn', payload: data });
localStorage.setItem('userInfo', JSON.stringify(data));
navigate(redirect || '/');
} catch (err) {
toast.error(getError(err));
console.log(err);
}
};
useEffect(() => {
if (userInfo) {
navigate(redirect);
}
}, [navigate, userInfo, redirect]);
return (
<Container className='small-container'>
<Helmet>
<title>Sign Up</title>
</Helmet>
<h1 className='my-3'>Sign Up</h1>
<Form onSubmit={submitHandler}>
<Form.Group className='mb-3' controlId='name'>
<Form.Label>Name</Form.Label>
<Form.Control
required
onChange={e => setName(e.target.value)}
/>
</Form.Group>
<Form.Group className='mb-3' controlId='email'>
<Form.Label>Email</Form.Label>
<Form.Control
type='email'
required
onChange={e => setEmail(e.target.value)}
/>
</Form.Group>
<Form.Group className='mb-3' controlId='password'>
<Form.Label>Password</Form.Label>
<Form.Control
type='password'
required
onChange={e => setPassword(e.target.value)}
/>
</Form.Group>
<Form.Group className='mb-3' controlId='confirmPassword'>
<Form.Label>Confirm Password</Form.Label>
<Form.Control
type='password'
required
onChange={e => setConfirmPassword(e.target.value)}
/>
</Form.Group>
<div className='mb-3'>
<Button type='submit'>Sign Up</Button>
</div>
<div className='mb-3'>
Already have an account?{' '}
<Link to={`/signin?redirect=${redirect}`}>Sign-In</Link>
</div>
</Form>
</Container>
);
}
userRouter.js
个
userRouter.post(
'/signup',
expressAsyncHandler(async (req, res) => {
const newUser = new User({
name: req.body.name,
email: req.body.email,
password: bcrypt.hashSync(req.body.password),
});
try {
const user = await newUser.save();
res.send({
_id: user._id,
name: user.name,
email: user.email,
isAdmin: user.isAdmin,
token: genarateToken(user),
});
} catch (err) {
res.status(500).send(err)
}
})
);
export default userRouter;
UserModel.js
个
const userSchema = new mongoose.Schema(
{
name: {type:String, required: true},
email: {type:String, required: true, unique:true},
password: {type:String, required: true},
isAdmin: {type: Boolean, default: false,required: true},
},
{
timestamps: true
}
)
const User = mongoose.model("User", userSchema);
export default User;
Routes in App.js
个
<Routes>
<Route path='/product/:slug' element={<ProductScreen />} />
<Route path='/cart' element={<CartScreen />} />
<Route path='/signin' element={<SignInScreen />} />
<Route path='/signup' element={<SignUpScreen />} />
<Route path='/shipping' element={<ShippingAddressScreen />} />
<Route path='/' element={<HomeScreen />} />
</Routes>
mongoURI in .env file
个
MongoURI = mongodb+srv://Ecom:password@cluster0.c0ita7f.mongodb.net/EcomDB?retryWrites=true&w=majority
Error in Console
个
AxiosError {message: 'Request failed with status code 500', name: 'AxiosError', code: 'ERR_BAD_RESPONSE', config: {…}, request: XMLHttpRequest, …}
code: "ERR_BAD_RESPONSE"
config: {transitional: {…}, transformRequest: Array(1), transformResponse: Array(1), timeout: 0, adapter: ƒ, …}
message: "Request failed with status code 500"
name: "AxiosError"
request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
response: {data: {…}, status: 500, statusText: 'Internal Server Error', headers: {…}, config: {…}, …}
[[Prototype]]: Error
error showing in postman
个
{
"code": 79,
"codeName": "UnknownReplWriteConcern",
"errInfo": {
"writeConcern": {
"w": "majority,",
"wtimeout": 0,
"provenance": "clientSupplied"
}
},
"result": {
"n": 1,
"electionId": "7fffffff0000000000000067",
"opTime": {
"ts": {
"$timestamp": "7136856325794824195"
},
"t": 103
},
"writeConcernError": {
"code": 79,
"codeName": "UnknownReplWriteConcern",
"errmsg": "No write concern mode named 'majority,' found in replica set configuration",
"errInfo": {
"writeConcern": {
"w": "majority,",
"wtimeout": 0,
"provenance": "clientSupplied"
}
}
},
"ok": 1,
"$clusterTime": {
"clusterTime": {
"$timestamp": "7136856325794824195"
},
"signature": {
"hash": "OlulLu5s5TwSvEO60v4+6td/yt8=",
"keyId": {
"low": 7,
"high": 1648401224,
"unsigned": false
}
}
},
"operationTime": {
"$timestamp": "7136856325794824195"
}
}
}