首先让我说我对MERN堆栈还很陌生。我一直在学习教程,但有些概念解释得不太好。
使用GET时,我调用/users。然而,根据教程,当我发布时,我必须发布到/user/new。不知道为什么它从复数(user(变成单数(user(。这是对express的警告,还是我在创建一条新路线?
我最大的问题是我不知道如何提交PUT请求。。。我无法更新对象中的任何信息。我还试图将信息添加到我的动物模型中的子数组中。
我将提供我的App.js、server.js和Model(Animal(、
SERVER.JS
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const twilio = require('twilio')
const app = express();
app.use(express.json());
app.use(cors());
mongoose.connect('mongodb://127.0.0.1:27017/newtable', {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => console.log("Connected to MongoDB")).catch(console.error);
app.listen(3008, () => console.log("Connected on Port 3008"));
const Animal = require('./models/Animals');
app.get('/animals', async(req, res) => {
const animals = await Animal.find()
res.json(animals)
})
app.post('/animals/new', (req, res) => {
const animal = new Animal({
phoneNumber: req.body.phoneNumber,
textHistory: req.body.textHistory,
name: req.body.name
})
animal.save()
res.json(animal)
})
app.delete('/animal/delete/:id', async (req, res) => {
const result = await Animal.findByIdAndDelete(req.params.id);
res.json({result});
});
app.put('/animal/update/:id', async (req, res) => {
const numba = await Animal.findOne(req.params.id);
numba.phoneNumber = "gordage"
numba.save();
res.json(numba);
console.log('asdfoij')
})
ANIMAL.JS(型号(
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const AnimalSchema = new Schema({
phoneNumber: {
type: String,
required: false
},
textHistory: {
type: String,
required: false
},
name: {
type: String,
required: false
}
});
const Animal = mongoose.model("Animal", AnimalSchema);
module.exports = Animal;
App.js
import React, {useState, useEffect} from "react"
import './App.css';
function App() {
const api_base = "http://localhost:3008"
const [animals, setAnimals] = useState([])
const GetAnimals = () => {
fetch(api_base + "/animals")
.then(res => res.json())
.then(data => setAnimals(data))
.catch((err) => console.error("error", err));
console.log(animals)
}
useEffect(() => {
GetAnimals()
}, [])
const deleteAnimal = async id => {
const data = await fetch(api_base + '/animal/delete/' + id, { method: "DELETE" }).then(res => res.json());
setAnimals(animals => animals.filter(animal => animal._id !== data.result._id));
console.log('working')
}
const addAnimal = async () => {
const data = await fetch(api_base + "/animals/new", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
phoneNumber: "9175028901",
textHistory: "benson",
name: "beni"
})
}).then(res => res.json());
setAnimals([...animals, data]);
console.log("clicking")
}
const changePhone = async id => {
const data = await fetch(api_base + '/animal/phoneNumber/' + id).then(res => res.json());
console.log("doing")
setAnimals(animals => animals.map(animal => {
if (animal._id === data._id) {
animal.phoneNumber = "bensonhurst";
}
return animal;
}));
console.log("doing")
}
return (
<div>
<h1>Welcome to Beni's Table</h1>
<table className="table">
<thead>
<tr>
<th>One</th>
<th>Two</th>
<th>Three</th>
<th>Four</th>
<th>Five</th>
</tr>
</thead>
</table>
<h1>Animal List</h1>
{animals.map(animal => (
<tbody>
<td>{animal.name}</td>
<td>{animal._id}</td>
<td>{animal.phoneNumber}</td>
<button onClick={() => changePhone(animal._id)}>Change Phone</button>
<button onClick={() => deleteAnimal(animal._id)}>X</button>
</tbody>
))}
<button onClick={addAnimal}>add</button>
</div>
);
}
export default App;
如何从客户端提交PUT请求。我认为这就是问题所在。您还没有在react和express中的changePhone方法的请求中指定方法PUT,端点是/amal/update/:id,您正在调用/amal/phoneNumber/。这就像与服务器通信一样,在请求选项中,我们指定他们嘿";快递服务器";我想使用PUT方法,所以请像您在POST中指定的那样更新数据。此外,直观地理解PUT方法的作用将对您有所帮助。(它通过覆盖现有数据来更新现有数据,从而取代源的原始版本(
所以两者的修复方法都是:
React:中的获取PUT请求
const requestOptions = {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: { Animal: 'The data you want to change the exisiting data with' }
};
fetch(`/animal/update/${id}`, requestOptions)
.then(response => response.json())
.then(data => console.log(data));
axios中的PUT请求(基于Promise的http客户端(:
const res = await axios.put(`/animal/update/${id}`, { Animal: 'The data you want to change the exisiting data with' });
这是客户端的Put请求。现在让Put方法在服务器端更加清晰。请参阅:https://thecodepixi.dev/blog/express-mongoose-crud-api/#updating-实例。