在这里,我试图通过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"
        }
    }
}

推荐答案

我在《postman 》中得了"errmsg": "No write concern mode named 'majority,' found in replica set configuration",分.我在.env文件中写入了我的MongoDB连接URL.

  1. 如果您将mongoURI代码放在单引号或分号中,则为.env file 一切都结束了.将出现以下错误.

  2. 删除mongoURI中?之后的代码我的错误消失了

    MongoURI = mongodb+srv://Ecom:password@cluster0.c0ita7f.mongodb.net/EcomDB?

从这个开始

MongoURI = mongodb+srv://Ecom:password@cluster0.c0ita7f.mongodb.net/EcomDB?retryWrites=true&w=majority

Reactjs相关问答推荐

从app.js导航,这是在BrowserRouter包装之外

Reactjs中的chartjs和reaction-chartjs-2的问题

如何将图像(在代码中称为自己)定位在蓝色圈内的点上?我正在使用material UI和Reaction

为什么登录错误和密码在创建Reaction-Hook-Form后立即被删除?

react 路由GUGUD Use Effect无法通过useNavigate正常工作

为什么我的react虚拟化列表不显示滚动条,除非我确保高度低于rowCount*rowHeight?

更改滑块标记的文本 colored颜色 ./Reaction/MUI 5

GitHub页面未正确显示Reaction应用程序网站

我如何在不被 destruct 的情况下将导航栏固定在顶部?

StrictMode+SetInterval=双重渲染(即使使用useEffect清理)

MUI 日期 Select 器 - 最小日期混乱

在 React 中是否有任何理由要记住 Redux 操作创建者?

React Router 6 点击链接在 React 18 应用中打开 flickr 页面

React 测试库包装器组件

cypress `cy.now()` Type 'Promise' 没有调用签名

如何使图标适合 react-bootstrap 中的行元素

如何使用react 路由将 url 参数限制为一组特定的值?

渲染的钩子比预期的少.这可能是由 React Hooks 中意外的提前返回语句引起的

使用 React 中的功能组件更改另一个组件的状态

调用函数以获取数据并在数据到达时导航到链接