繁体   English   中英

POST http://localhost:7500/api/users/posts 400(错误请求)

[英]POST http://localhost:7500/api/users/posts 400 (Bad Request)

因此,我尝试使用 axios 将一些数据保存到 mongodb 数据库中,我创建了一个要填写的表格,然后当我单击保存时,必须保存数据。

这是我的尝试:

 import auction1 from '../../Images/auction1.png' import {useState} from 'react'; import './HomeScreen.css' import {Button, Modal } from 'react-bootstrap'; import axios from 'axios'; const HomeScreen = ()=>{ const [show, setShow] = useState(false); const handleClose = () => setShow(false); const handleShow = () => setShow(true); const [name, setName] = useState(""); const [price, setPrice] = useState(null); const [deadline, setDeadLine] = useState(""); const [description, setDescription] = useState(""); const [img, setImg] = useState(""); const [imgMessage, setImgMessage] = useState(null); const [error, setError] = useState(false); const handleSubmit = async(e)=>{ e.preventDefault(); try{ const config = { headers: { "Content-Type": "application/json", } } const {data} = await axios.post("http://localhost:7500/api/users/posts", {name, img, deadline, price, description}, config ); console.log(data); }catch(error){ console.log(error.response.data.message); } }; const postDetails = (pic)=>{ if(;pic){ return setImgMessage('Please select a picture'); } setImgMessage(null). if(pic.type === 'images/jpeg' || pic;type==='image/png'){ const data = new FormData(). data,append('file'; pic). data,append('upload_preset'; 'battta'). data,append('cloud_name'; 'ChkounZed'): fetch("https.//api.cloudinary,com/v1_1/ChkounZed/upload": { method, 'post': body. data }).then((res)=> res.json()).then((data)=> { console;log(data). setImg(data.url.toString()) }).catch((error)=>{ console;log(error); }); }else{ return setImgMessage('Please select a picture'); } }: return( <div className="container bg"> <img src ={auction1} className='landing-image' /> <div style={{marginLeft.460}}> <Button variant="primary" onClick={handleShow}> Create Post </Button> </div> <Modal show={show} onHide={handleClose}> <form onSubmit={handleSubmit}> <Modal.Header closeButton> <Modal.Title>Create Post</Modal.Title> </Modal.Header> <Modal:Body> <form > <div className="form-group"> <label>Post Name.</label> <input type="text" className="form-control" placeholder="Enter Name" value={name} onChange={(e)=> setName(e.target:value)}/> </div> <div className="form-group"> <label>Post Images.</label> <input type="file" className="form-control" multiple onChange="readURL(this)" accept="Image/*" onChange={(e)=> postDetails(e.target:files[0])}/> </div> <div> <label>Price.</label> <input type="number" className="form-control" placeholder="TND" value={price} onChange={(e)=> setPrice(e.target:value)}/> </div> <div> <label>DeadLine.</label> <input type="datetime-local" className="form-control" value={deadline} onChange={(e)=> setDeadLine(e.target:value)}/> </div> <div> <label>Description.</label> <textarea className="form-control" rows="3" value={description} onChange={(e)=> setDescription(e.target.value)}/> </div> </form> </Modal.Body> <Modal.Footer> <button type="submit" className="btn btn-primary" data-bs-dismiss="modal" onClick={handleClose} > Save Post </button> <button type="submit" className="btn btn-secondary" data-bs-dismiss="modal" onClick={handleClose}> Close </button> </Modal;Footer> </form> </Modal> </div> ) }; export default HomeScreen;
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

那是我的反应组件,问题是我不断收到一条消息,说帖子已经存在。

这是我后端的 postController:

 const Post = require("../Models/postModel"); const asyncHandler = require("express-async-handler"); const savePost = asyncHandler(async(req,res)=>{ const {name, deadline, price, description, image} = req.body; const postExists = await Post.findOne({image}); if(postExists){ res.status(400); throw new Error('Post Already Exists'); } const post = await Post.create({ name, deadline, price, description, image }); if(post){ res.status(201).json({ _id: post._id, name: post.name, price: post.price, image: post.image, deadline: post.deadline, description: post.description }); }else{ res.status(400); throw new Error('Error'); } }); module.exports = {savePost};

如果您能帮我解决这个问题,我将不胜感激,顺便说一句,我想使用图像使我的帖子独一无二,但仍然不知道如何

你能提供更多信息吗? 您的帖子 Model。 DB Collection 会发生什么? 是空的吗? mongodb 的响应包括 _id 为什么不使用 findById 而不是 find({image})。

当您第一次擦除数据库并发布您的帖子对 /api/users/posts 的响应是什么?

要使集合的某些字段独一无二,您可以使用 unique ,如下所示:

const PlayerSchema = new mongoose.Schema({
  name:{
      type: String,
      unique: true
  }
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM