提取POST请求后发生422无法处理的实体错误

时间:2020-01-14 21:43:20

标签: node.js reactjs fetch

我收到422无法处理的实体,发出提取POST请求时输入无效错误。这导致我的请求有效载荷中有一个空对象{}。

我已经做了以下检查。请看一下,并请正确的方向引导我。

•检查后路线

router.post(
      '/',
      [
        check('location').not().isEmpty(),
        check('caption').not().isEmpty()
      ],
      postsControllers.createPost
    );

•检查了员额控制器,从正文中提取了正确的属性

const { userId, location, caption } = req.body;

const createdPost = new Post({
  userId,
  location,
  imageUrl: 'abc.jpeg',
  caption,
})

•检查是否在前端auth-context中管理userId

// auth-context
export const AuthContext = createContext({
  isLoggedIn: false,
  userId: null,
  login: () => {},
  logout: () => {}
});

// App.js
const login = useCallback((uid) => {
  setIsLoggedIn(true);
  setUserId(uid);
}, []);

const logout = useCallback(() => {
  setIsLoggedIn(false);
  setUserId(null);
}, []);

•检查用户属性是否在注册和登录时映射到用户对象

// signup action of users-controllers
res.status(201).json({ user: createdUser.toObject({ getters: true })});

// login action of users-controllers
res.json({ message: 'Logged in!', user: existingUser.toObject({ getters: true })});

•检查在新帖子中发送请求时是否包含url,请求,正文和标头

// New Post
<Formik
  initialValues={‌{ location: '', caption: ''}}
  validationSchema={validationSchema}
  onSubmit={(values, { setSubmitting }) => {
    try {
      fetch('http://localhost:5000/api/posts', {
      method: 'POST',
      headers: {
    'Content-Type': 'application/json'
      },
      body: JSON.stringify({
    userId: auth.userId,
    email: values.email,
    password: values.password
      })
    )
  history.push('/');
  } catch (err) {}
}}

enter image description here

0 个答案:

没有答案