简体   繁体   English

在 React.js 中使用 Fetch API 发送 PUT 数据

[英]Sending PUT data using Fetch API in React.js

My GET routes are working fine, but seems to not be able to get my data to my PUT route.我的 GET 路线工作正常,但似乎无法将我的数据传送到我的 PUT 路线。 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.第一个文件,称为“saveOverTemplate”的方法,应该获取我的组件的内容,并将其发送到我的 PUT 路由以在我的数据库中更新。 If I console.log the data in the "saveOverTemplate" method, it is exactly as expected.如果我 console.log 在“saveOverTemplate”方法中记录数据,它完全符合预期。 And, when I click the button, the first console.log shows that I did indeed reach the method.而且,当我单击按钮时,第一个 console.log 显示我确实到达了该方法。 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.然后这是包含我的路线的文件,我似乎无法在我的 PUT 方法中正确导入数据。 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.');
});


Don't forget to include headers when using fetch:使用 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文档: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM