0

My GET routes are working fine, but seems to not be able to get my data to my PUT route. This first file, the method called "saveOverTemplate", is supposed to take the content of my component, and send it to my PUT route to be updated in my database. If I console.log the data in the "saveOverTemplate" method, it is exactly as expected. And, when I click the button, the first console.log shows that I did indeed reach the method. However when I try to log the data, it just shows as "undefined". Can anyone see what I'm missing in how I'm sending the data over?

//My React Component

import React, { Component } from 'react';
import { Editor } from '@tinymce/tinymce-react';

let policyContent = '';

class TinyEditor extends Component {
    constructor(props) {
        super(props);

        this.state = { content: '' };

        this.handleEditorChange = this.handleEditorChange.bind(this);
        this.handleClick = this.handleClick.bind(this);
        this.saveOverTemplate = this.saveOverTemplate.bind(this);

    }

    componentDidMount() {
        console.log(`Component did mount`);
        fetch(`/api/policy`)
            .then(res => res.json())
            .then((result) => {
                console.log(result);
                policyContent = result;
                this.setState({ content: policyContent[0].contents });
            });
    }

    handleEditorChange(content, editor) {
        this.setState({ content });
    }

    handleClick(e) {
        e.preventDefault();
        console.log(`Button was clicked.`);
        console.log(this.state.content);
        this.setVariables('Company}}', 'Variable');
    }

    setVariables(search, replaceWith){
        const result = this.state.content.split(search).join(replaceWith);
        this.setState({content: result});
    }   

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

    render() {
        return (
            <div>
                <div className="container">
                    <Editor
                        apiKey='yf9eajz93s3akrlb24b8ja9xcszddbxx22x4ug8c2q5boxw3'
                        className="mceEditor"
                        id='myTextArea'
                        init={{
                            height: 500,
                            editor_selector: 'mceEditor',
                            menubar: false,
                            browser_spellcheck: true,
                            contextmenu: true,
                            branding: false,
                            plugins: [
                                'advlist autolink lists link image charmap print preview anchor',
                                'searchreplace visualblocks code fullscreen',
                                'insertdatetime media table paste code help wordcount'
                            ],
                            toolbar:
                                'undo redo | formatselect | bold italic backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | help'
                        }}
                        onEditorChange={this.handleEditorChange}
                        value={this.state.content}
                    />
                    <button onClick={this.handleClick}>Save</button>
                    <button onClick={this.saveOverTemplate}>Save Over Template</button>
                    <div dangerouslySetInnerHTML={{__html: this.state.content}}></div>
                </div>
            </div>
        )
    }
}

export default TinyEditor;

Then this is the file that has my routes, where I can't seem to bring in the data correctly in my PUT method. Please help!

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.');
});


2 Answers 2

1

Don't forget to include headers when using 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));
    }

Documentation: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I added those and got the same. But it started working when I simply added the app.use(bodyParser.json()). I can't believe it was that simple.
0

make sure you understand it first

async function handleUpdate() {
    const res = await fetch('https://jsonplaceholder.typicode.com/users/1', {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        name: 'navdeep Singh',
        username: 'navi',
        email: '[email protected]'
      })
    })
    console.log(res.status)
    const result = await res.json()
    console.log(result)
    if (res.status === 200) {
      alert('Data updated successfully')
    }
  }
  handleUpdate()

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.