[英]I am making a cutomer profile (a sample) and I am getting the error - POST http://localhost:3000/cusprofiles/add 400 (Bad Request) when I add data
I want to make a customer profile for a vet clinic and according to my code, I am unable to insert and edit customer details.我想为兽医诊所制作客户资料,但根据我的代码,我无法插入和编辑客户详细信息。 I cannot find where I have gone wrong.
我找不到哪里出错了。 Only get method is working.
只有 get 方法有效。 Can someone help me please?
有谁可以帮助我吗?
This is my js file in models这是我在模型中的 js 文件
const Schema = mongoose.Schema;
const cusprofileSchema = new Schema({
Pet_Name: {type: String, requied : true},
Owner_Name: {type: String, required:true},
PetAge: {type: String, required:true},
cusprofileImage: {type: String, required: true},
vaccination: {type: String, required:true},
medication: {type: String, required:true},
other: {type: String, required:true},
next_meetup: {type: Date, required:true},
});
const CusProfiles = mongoose.model("CusProfiles", cusprofileSchema);
module.exports = CusProfiles;
This is my js file in routes这是我在路线中的js文件
const res = require("express/lib/response");
const { default: mongoose } = require("mongoose");
const router = express.Router();
const multer = require("multer");
const CusProfiles = require('../models/cusprofiles');
const Medication = require('../models/cusprofiles')
const storage = multer.diskStorage({
destination: (req, file, callback) => {
callback(null, "./vet/public/uploads/");
},
filename: (req, file, callback) => {
callback(null, file.originalname);
}
});
const upload = multer({storage: storage});
//Request get all profiles
router.get('/', (req, res)=> {
CusProfiles.find()
.then(cusprofile => res.json(cusprofile))
.catch(err => res.status(400).json('Error: $(err'))
});
//Request get all profiles
router.get('/view', (req, res)=> {
Medication.find()
.then(cusprofile => res.json(cusprofile))
.catch(err => res.status(400).json('Error: $(err'))
});
//Request add new profile
router.post('/add', upload.single("cusprofileImage"), (req, res) => {
const newCusProfile = new CusProfiles({
Pet_Name: req.body.Pet_Name,
Owner_Name: req.body.Owner_Name,
PetAge: req.body.PetAge,
cusprofileImage: req.file.originalname,
vaccination: req.body.vaccination,
medication: req.body.medication,
other: req.body.other,
next_meetup: Date(req.body.next_meetup),
});
newCusProfile.save()
.then(() => res.json("The new Profile posted successfully!"))
.catch(err => res.status(400).json('Error: ${err}'));
});
//Request find profile by Id
router.get("/:id", (req, res) => {
CusProfiles.findById(req.params.id)
.then(cusprofile => res.json(cusprofile))
.catch(err => res.status(400).json('Error: ${err}'));
});
//Request find profile by Id and update
router.put("/update/:id", upload.single("cusprofileImage"), (req, res) => {
CusProfiles.findById(req.params.id)
.then(cusprofile => {
cusprofile.Pet_Name = req.body.Pet_Name;
cusprofile.Owner_Name = req.body.Owner_Name;
cusprofile.PetAge = req.body.PetAge;
cusprofile.cusprofileImage = req.file.originalname;
cusprofile.vaccination = req.body.vaccination;
cusprofile.medication = req.body.medication;
cusprofile.other = req.body.other;
cusprofile.next_meetup = Date(req.body.next_meetup);
cusprofile
.save()
.then(() => res.json("The Profile is Updated successfully"))
.catch(err => res.status(400).json('Error: ${err}'));
})
.catch(err => res.status(400).json('Error: ${err}'));
});
//Request find profile by Id and delete
router.delete("/:id", (req, res) =>{
CusProfiles.findByIdAndDelete(req.params.id)
.then(() => res.json("The profile is DELETED!"))
.catch(err => res.status(400).json('Error: ${err}'));
});
module.exports = router;
**what includes in server**
const mongoose = require("mongoose");
const cors = require("cors");
require('dotenv').config();
const app = express();
const port = process.env.PORT || 8080;
app.use(cors());
app.use(express.json());
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, {
useNewUrlParser:true,
useUnifiedTopology:true
});
const connection = mongoose.connection;
connection.once("open", ()=>
console.log("MongoDB connection established successfully!")
);
const cusprofilesRouter = require("./routes/cusprofiles.js");
app.use("/cusprofiles", cusprofilesRouter);
app.listen(port, () => console.log('The app is running on Port: ${port}'));
This is my App.js这是我的 App.js
import {Route} from "react-router-dom";
import axios from "axios";
import "./App.css";
import "bootstrap/dist/css/bootstrap.min.css";
import Header from "./components/layouts/Header";
import Navbar from "./components/layouts/Navbar";
import Footer from "./components/layouts/Footer";
import CusProfiles from "./components/CusProfiles";
import CusProfile from "./components/CusProfile";
import AddNewMedication from "./components/AddNewMedication";
import EditMedication from "./components/EditMedication";
import AddCusProfile from "./components/AddCusProfile";
import EditCusProfile from "./components/EditCusProfile";
import Medication from "./components/Medication";
function App() {
const [posts, setPosts] = useState([]);
useEffect(()=> {
axios
.get("/cusprofiles")
.then(res => setPosts(res.data))
.catch(error => console.log(error));
});
return (
<div className="App">
<Header/>
<Navbar/>
<Route
exact path="/view"
render={() => <Medication posts={posts}/>}
/>
<Route exact path="/" render={() => <CusProfiles posts={posts}/>}
/>
<Route
path="/cusprofile/:id"
render={(props) => <CusProfile {...props} posts={posts}/>}
/>
<Route
path="/add"
render={(props) => <AddNewMedication {...props} posts={posts}/>}
/>
<Route
path="/update/:id"
render={(props) => <EditMedication {...props} posts={posts}/>}
/>
<Route
path="/update/:id"
render={(props) => <EditCusProfile {...props} posts={posts}/>}
/>
<Route exact path="/add-profile" component={AddCusProfile}/>
{/*<Route exact path="/edit-profile" component={EditCusProfile}/>*/}
<Footer/>
</div>
);
}
export default App;
This is AddCusProfile.js这是 AddCusProfile.js
import styled from "styled-components";
import axios from "axios";
const AddCusProfile = () => {
const [Pet_Name, setPetName] = useState("");
const [Owner_Name, setOwnerName] = useState("");
const [PetAge, setAge] =useState("");
const [vaccination, setVacc] =useState("");
const [medication, setMedi] =useState("");
const [other, setOther] =useState("");
const [next_meetup, setMeet] =useState("");
const [message, setMessage] = useState("");
const [fileName, setFileName] = useState("");
const onChangeFile = e => {
setFileName (e.target.files[0]);
}
const changeOnClick = (e) => {
e.preventDefault();
const formData = new FormData();
formData.append("Pet_Name", Pet_Name);
formData.append("Owner_Name", Owner_Name);
formData.append("PetAge", PetAge);
formData.append("vaccination", vaccination);
formData.append("medication", medication);
formData.append("other", other);
formData.append("next_meetup", next_meetup);
formData.append("cusprofileImage", fileName);
setPetName("");
setOwnerName("");
setAge("");
setVacc("");
setMedi("");
setOther("");
setMeet("");
axios.post("/cusprofiles/add", formData)
.then(res => setMessage(res.data))
.catch(err => {
console.log(err);
});
};
return (
<AddProfileContainer>
<div className="container">
<h1>Add New Pet Profile</h1><br></br>
<span className="message">{message}</span><br></br>
<form onSubmit={changeOnClick} encType="multipart/form-data">
<div className="form-group">
<label htmlFor="Pet_Name">Pet Name</label>
<input
type="text"
value={Pet_Name}
onChange={e => setPetName(e.target.value)}
className="form-control"
placeholder="Enter Pet Name"></input><br></br>
</div>
<div className="form-group">
<label htmlFor="Owner_Name">Owner Name</label>
<input
type="text"
value={Owner_Name}
onChange={e => setOwnerName(e.target.value)}
className="form-control"
placeholder="Enter Owner Name"></input><br></br>
</div>
<div className="form-group">
<label htmlFor="PetAge">Pet Age</label>
<input
type="text"
value={PetAge}
onChange={e => setAge(e.target.value)}
className="form-control"
placeholder="Enter Pet Age"></input><br></br>
</div>
<div className = "form-group">
<label htmlFor="file">Choose Profile Image</label><br></br>
<input
type="file"
filename = "cusprofileImage"
className="form-control-file"
onChange={onChangeFile}
/><br></br><br></br>
</div>
<button type="submit" className="btn btn-primary">
Submit Details
</button>
</form>
</div>
</AddProfileContainer>
)
};
export default AddCusProfile;
//Main Container
const AddProfileContainer = styled.div`
margin: 3rem auto;
padding: 4rem;
width: 51.25rem;
h1 {
font-weight:900;
color: var(--dark-green);
}
.btn-primary {
margin-top: 2rem;
background: var(--dark-green);
border:none;
&:hover {
background: var(--light-green);
}
}
.message {
font-weight: 900;
color: tomato;
padding: 1rem 1rem 1rem 0;
}
`;
In my opinion you should use findByIdAndUpdate(),
instead of findById
in router.put method.在我看来,您应该在 router.put 方法中使用
findByIdAndUpdate(),
而不是findById
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.