简体   繁体   English

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

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

So I am trying to save some data into a mongodb data base using axios I created a form to fill then when i click on save the data must be saved.因此,我尝试使用 axios 将一些数据保存到 mongodb 数据库中,我创建了一个要填写的表格,然后当我单击保存时,必须保存数据。

this is my try:这是我的尝试:

 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>

that was my react component and the problem is that i keep getting a message that says the post already exists.那是我的反应组件,问题是我不断收到一条消息,说帖子已经存在。

this is my postController from the backend side:这是我后端的 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};

I would be so grateful if you can give me hand of this and by the way i wanna make my post unique using the images and still did not know how如果您能帮我解决这个问题,我将不胜感激,顺便说一句,我想使用图像使我的帖子独一无二,但仍然不知道如何

Can you provide more information?你能提供更多信息吗? Your Post Model.您的帖子 Model。 What happens at the DB Collection? DB Collection 会发生什么? Is it empty?是空的吗? The response of mongodb includes _id why not use findById instead of find({image}). mongodb 的响应包括 _id 为什么不使用 findById 而不是 find({image})。

When u wipe your database and post the first time whats the response of your post to /api/users/posts?当您第一次擦除数据库并发布您的帖子对 /api/users/posts 的响应是什么?

To make some fields unique for the collection you can use unique like below:要使集合的某些字段独一无二,您可以使用 unique ,如下所示:

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

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

相关问题 POST http://localhost:3000/api/signup 400(错误请求) - POST http://localhost:3000/api/signup 400 (Bad Request) POST http://localhost:3000/updateSurvey 400(错误请求) - POST http://localhost:3000/updateSurvey 400 (Bad Request) HTTP POST -&gt; 400:错误请求 - HTTP POST -> 400: Bad Request http://localhost:8000/token/ 400(错误请求) - http://localhost:8000/token/ 400 (Bad Request) Api 发布 400 错误请求 - Api Post 400 Bad Request POST http:// localhost:51348 / TestService.svc / SendCredentials 400(错误请求) - POST http://localhost:51348/TestService.svc/SendCredentials 400 (Bad Request) 尝试将数据从客户端发送到服务器时,POST http://localhost:3000/data 400(错误请求) - POST http://localhost:3000/data 400 (Bad Request) when trying to send data from client to server $ http发布方法的400错误请求 - 400 Bad Request for $http post method AngularJS $http / .NET Web API - 获取 400(错误请求)或 NULL POST 操作方法参数 - AngularJS $http / .NET Web API - Either Getting 400 (Bad Request) or NULL POST Action Method Parameter 在 ejs 和 nodejs 中发布 http://localhost:3000/socket.io/?EIO=3&amp;transport=polling&amp;t=NQUneY3 400(错误请求) - POST http://localhost:3000/socket.io/?EIO=3&transport=polling&t=NQUneY3 400 (Bad Request) in ejs and nodejs
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM