【问题标题】:MERN API request, don't know how to make a put request and update properlyMERN API 请求,不知道如何发出 put 请求并正确更新
【发布时间】:2022-01-09 11:43:45
【问题描述】:

首先让我说我是 MERN 堆栈的新手。我一直在通过教程学习,但是有些概念没有很好地解释。

使用 GET 时,我调用 /users。但是根据教程,当我发布时,我必须发布到 /user/new。不知道为什么它从复数(用户)变为单数(用户)。这是对 express 的警告,还是我正在创建一条新路线?

我最大的问题是我不知道如何提交 PUT 请求...我无法更新对象中的任何信息。我也在尝试将信息添加到我的 Animal 模型中的子数组中。

我将提供我的 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;

【问题讨论】:

  • 您可以使用postman 来协助您向您的服务器发送任何请求,还有其他软件您可以探索
  • 我正在使用 REST 客户端,仍然没有运气.. 我无法通过 put 请求。我认为我的语法是错误的。
  • 你的意思是你的 App.js 吗?我没有看到任何方法:“PUT”
  • GET /users - API 获取所有用户 | POST /user/new - API 创建 1 个新用户 基本上为什么教程使用用户而不是用户

标签: node.js reactjs mongodb mongoose


【解决方案1】:

如何从客户端提交 PUT 请求。我认为这是问题所在。您没有在 changePhone 方法的请求中指定方法 PUT 反应和快递端点是 /animal/update/:id 并且您正在调用 /animal/phoneNumber/。这就像与服务器通信,在请求选项中我们指定它们嘿“快速服务器”我想使用 PUT 方法所以请更新数据就像您在 POST 中指定的一样。还可以直观地了解 PUT 方法的作用会对您有所帮助。 (它会根据 id 通过覆盖它来更新现有数据,从而替换源的原始版本)

所以对两者的修复将是:

在 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-instances

【讨论】:

  • 谢谢。你有没有机会知道猫鼬的语法?另外,您将这个 Fetch PUT 请求放在哪里?我似乎仍然无法继续..
  • 我遇到了同样的问题......现在已经坚持了 2 天了。
  • Fetch put 请求应根据选择放置。例如:一个带有文本更新的按钮,我们制作处理程序,并将整个修改后的数据与正文中的放置请求一起发送。所以我们要做的是发送一个 id ,服务器将搜索该 id ,获取我们的请求正文并将其替换为新数据。这就是 PUT 方法的要点。在猫鼬只是谷歌它你会发现很多资源。还在回答中分享了一个链接。
  • 用户想要编辑特定 id 的动物数据。在前端,他将单击按钮编辑。然后他会得到一个表格或任何东西来更新数据。我们会问他添加新数据。他会进去的。我们可以收集这些数据。跟踪它的状态。根据选择制作一个 onClick 处理程序或提交按钮。 (这一切都取决于您希望前端如何。我只是在给您 PUT 的直觉)。然后 fetch 或 axios put 请求将转到服务器。服务器将更新该 id 的查找数据并将其替换为新的。注意:PATCH 和 PUT 是不同的。
  • mongoosejs.com/docs/tutorials/findoneandupdate.html findOneandUpdate Mongoose 语法的官方文档。这将在将更新数据的服务器端端点上。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-20
  • 1970-01-01
相关资源
最近更新 更多