Отправка данных PUT с использованием Fetch API в React. js - PullRequest
0 голосов
/ 29 мая 2020

Мои маршруты GET работают нормально, но, похоже, не могут получить мои данные на моем маршруте PUT. Этот первый файл, метод под названием «saveOverTemplate», должен принимать содержимое моего компонента и отправлять его на мой маршрут PUT для обновления в моей базе данных. Если я console.log данные в методе «saveOverTemplate», это будет именно так, как ожидалось. И когда я нажимаю кнопку, первый console.log показывает, что я действительно достиг метода. Однако, когда я пытаюсь зарегистрировать данные, они просто отображаются как «undefined». Может ли кто-нибудь увидеть, что мне не хватает в том, как я отправляю данные? мой метод PUT. Пожалуйста, помогите!

const express = require('express');
const bodyParser = require ('body-parser');
const mysql = require('mysql2');

const connection = mysql.createPool({
    host        : 'localhost',
    user        : 'root',
    password    : '',
    database    : 'book'
});

const app = express();
app.use(bodyParser.urlencoded({ extended: false}));

// Creating a GET route that returns data from the 'users' table.
app.get('/api/policy/all', function (req, res) {
    // Connecting to the database.
    connection.getConnection(function (err, connection) {

        // Executing the MySQL query (select all data from the 'handbook' table).
        connection.query("SELECT * FROM handbook", function (error, results, fields) {
            // If some error occurs, we throw an error.
            if (error) throw error;

            // Getting the 'response' from the database and sending it to our route. This is were the data is.
            res.json(results);
        });
    });
});

app.get('/api/policy', function (req, res) {
    // Connecting to the database.
    connection.getConnection(function (err, connection) {

        // Executing the MySQL query (select all data from the 'handbook' table).
        connection.query("SELECT contents FROM handbook WHERE policy = 'Benefits' ", function (error, results, fields) {
            // If some error occurs, we throw an error.
            if (error) throw error;

            // Getting the 'response' from the database and sending it to our route. This is were the data is.
            res.json(results);
        });
    });
});

app.put('/api/policy/update', function(req, res) {
    console.log('It is getting to the route');
    const data = req.body.content;
    console.log(data);
    // connection.getConnection(function(err, connection) {
    //     connection.query("UPDATE handbook SET contents= WHERE policy = 'Benfits'", function(error, results, fields){
    //         if(error) throw error;
    //         res.json(results);
    //         console.log(`Has been put`);
    //     });
    // });
});


// Starting our server.
app.listen(3001, () => {
    console.log('Go to http://localhost:3001/policy so you can see the data.');
});


1 Ответ

1 голос
/ 29 мая 2020

Не забудьте включить заголовки при использовании fetch:

saveOverTemplate(e) {
        e.preventDefault();
        let content = this.state.content
        console.log(content);
        fetch(`/api/policy/update`, {
            method: 'PUT',
            body: JSON.stringify({content}),
            headers: {"Content-Type": "application/json"}
        })
        .then(res => res.json())
        .then(data => console.log(data))
        .catch(err => console.log(err));
    }

Документация: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...