如何解决 React 中的 Loopback 4 POST 数据 422 错误?

时间:2021-01-30 12:53:09

标签: reactjs loopback

我使用环回 4 创建了一个简单的项目来为我的 React 应用程序生成端点。在 Openapi 接口中发布和获取数据工作正常。但是当我使用 fetch() 在 react 中发布数据时,它会在控制台中引发 422。有人可以告诉我如何解决这个问题吗?

数据库:Mongodb, id 类型:数字

下面是我的代码:

Error Message: 
{error: {statusCode: 422, name: "UnprocessableEntityError",…}}
code: "VALIDATION_FAILED"
details: [{path: "", code: "additionalProperties", message: "should NOT 
have additional 
properties",…},…]
0: {path: "", code: "additionalProperties", message: "should NOT have 
additional properties",…}
1: {path: "", code: "required", message: "should have required property 
'title'",…}
message: "The request body is invalid. See error object `details` property 
for more info."
name: "UnprocessableEntityError"
statusCode: 422

==========================================
  COMPONENT
===========================================

const CreateNews = () => {
    const [ newsdata, setNewsdata ] = useState({
       title:"",
       body: "",
      author: ""
    })

   const onSubmit = (e) => {
      e.preventDefault()
           
    fetch("http://localhost:8000/news", {
      method:"POST",
      headers:{ "Content-Type":"application/json"  },
      body: JSON.stringify({news:newsdata})
    }).then(() => console.log("success"))
    .catch(err => console.log(err))
 
  }

  return (
      <Container component="main" maxWidth="md" style={{marginTop: 20}}>
         <Paper elevation={3} style={{padding: 35}}>
         <Typography variant="h4">Create News</Typography>
         <form onSubmit={onSubmit}>
         <TextField 
          name="title"
          value={newsdata.title}
          label="Title"
          onChange={(e) => setNewsdata({...newsdata, title: e.target.value})}
          fullWidth
        />
        <TextField
          name="body"
          value={newsdata.body}
          type="textarea"
          label="Body"
          onChange={(e) => setNewsdata({...newsdata, body: e.target.value})}
          fullWidth
        />
        <TextField
          name="author"
          value={newsdata.author}
          label="Author"
          onChange={(e) => setNewsdata({...newsdata, author: e.target.value})}
          fullWidth
        />
        <Button type="submit">Create</Button>
      </form>
    </Paper>
  </Container>
  );
}

export default CreateNews

0 个答案:

没有答案