в приложении PERN запрос PUT не проходит в веб-приложении, хотя это происходит в Postman - PullRequest
1 голос
/ 04 августа 2020

Я создал приложение PERN todo. Я впервые создаю приложение, в котором серверная часть подключается к интерфейсу с базой данных.

У меня проблема с запросом на размещение. Это работает в Postman.

Но в браузере это не работает. Я получаю ошибку кода состояния 400.

Я потратил почти неделю на исследования, чтобы выяснить это, но пока не смог заставить его работать. Было бы хорошо, если бы кто-нибудь мог мне помочь. Я был бы очень признателен, если бы кто-нибудь мог объяснить, что происходит, и дать мне решение.

Заранее большое спасибо. изображение ошибки внешний интерфейс - реагировать EditTodo. js:

import React from 'react';
import M from "materialize-css";

export default class EditTodo extends React.Component {

    constructor(props) {
        super (props);
        this.state = {
            todo_id: this.props.todo.todo_id,
            description: this.props.todo.description
        }
    }

    componentDidMount() {
        const options = {
            onOpenStart: () => {
            console.log("Open Start");
        },
            onOpenEnd: () => {
            console.log("Open End");
        },
            onCloseStart: () => {
            console.log("Close Start");
        },
            onCloseEnd: () => {
            console.log("Close End");
        },
            inDuration: 250,
            outDuration: 250,
            opacity: 0.5,
            dismissible: false,
            startingTop: "4%",
            endingTop: "10%"
        };
        M.Modal.init(this.Modal, options);

        // let instance = M.Modal.getInstance(this.Modal);
        // instance.open();
        // instance.close();
        // instance.destroy();
    }

    editing = e => {
        console.log(e.target.value);
        this.setState({
            description: e.target.value
        })
    }

    updateSubmit = async e => {
        e.preventDefault();

        try {
            const body = this.state.description;
            const id = this.state.todo_id;

            if(body.description === "") throw new Error("Input cannot be empty");
            const response = await fetch(`http://localhost:5000/todos/${id}`, {
                method: "PUT",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify(body)
            });


            console.log(response);
            // window.location = "/";
        } catch (err) {
            console.log(err.message)
        }
    }

    render() {
        // console.log(this.props)
        // console.log(this.props.todo)
        // console.log(this.props.children)

        return (
            <>
                <a
                    className="waves-effect waves-light btn modal-trigger yellow blue-text"
                    data-target={ "modal" + this.props.index }
                >
                    Edit
                </a>

                <div
                    ref={Modal => {
                        this.Modal = Modal;
                    }}
                    id={ "modal" + this.props.index }
                    className="modal"
                >
                    {/* If you want Bottom Sheet Modal then add
                        bottom-sheet class to the "modal" div
                        If you want Fixed Footer Modal then add
                        modal-fixed-footer to the "modal" div*/}

                    <form onSubmit={this.updateSubmit}>
                        <div className="modal-content">
                            <h4>Edit a todo</h4>
                            <input
                                type="text"
                                onChange={this.editing}
                                value={this.state.description}
                            />
                        </div>

                        <div className="modal-footer">
                            <button type="submit" className="modal-close waves-effect orange waves-yellow btn-flat">Edit</button>
                            <a className="modal-close waves-effect green waves-red btn-flat">Close</a>
                        </div>
                    </form>
                </div>
            </>
        )
    }
}

внешний интерфейс - реагировать пакет. json:

{
  "name": "frontend-client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.3.2",
    "@testing-library/user-event": "^7.1.2",
    "materialize-css": "^1.0.0",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-scripts": "3.4.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

задний конец - узел : index. js

const express = require("express");
const app = express();

const cors = require("cors");
const pool = require("./db");

// middleware
app.use(cors())
app.use(express.json()) // req.body


// Routes ----------------------


// Update: edit todo
app.put("/todos/:id", async (req, res) => {
    const { id } = req.params;
    const { description } = req.body;
    const updateTodo = await pool.query("UPDATE todo SET description = $1 WHERE todo_id = $2", [description, id]);
    
    res.json("todo was updated");
})

app.listen(5000, () => {
    console.log("server has started on port 5000")
})

1 Ответ

0 голосов
/ 04 августа 2020

Кажется, ваш body отправляет только string, а не объект с полем description внутри.

const body = this.state.description;
const id = this.state.todo_id;

if(body.description === "") throw new Error("Input cannot be empty");
const response = 
     await fetch(`http://localhost:5000/todos/${id}`, {
                method: "PUT",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify(body)
            });

у вас есть эта проверка: if(body.description === "") но это не так работает, так как ваш body.description не определен, а не пустая строка.

Попробуйте отправить объект в свое тело, например, например:

const body = {
  description: this.state.description
};
const id = this.state.todo_id;

if(body.description === "") throw new Error("Input cannot be empty");
const response = 
     await fetch(`http://localhost:5000/todos/${id}`, {
                method: "PUT",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify(body)
            });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...