Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/41.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在React.js中使用Fetch API发送PUT数据_Javascript_Node.js_Reactjs_Express_Fetch - Fatal编程技术网

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

Javascript 在React.js中使用Fetch API发送PUT数据,javascript,node.js,reactjs,express,fetch,Javascript,Node.js,Reactjs,Express,Fetch,我的GET路由工作正常,但似乎无法将数据获取到PUT路由。第一个文件是名为“saveOverTemplate”的方法,它应该获取我的组件的内容,并将其发送到我的PUT路径,以便在数据库中进行更新。如果我将console.log数据记录在“saveOverTemplate”方法中,它与预期完全一样。当我单击按钮时,第一个console.log显示我确实找到了方法。但是,当我尝试记录数据时,它只显示为“未定义”。有人能看出我在如何发送数据时遗漏了什么吗 //My React Component i

我的GET路由工作正常,但似乎无法将数据获取到PUT路由。第一个文件是名为“saveOverTemplate”的方法,它应该获取我的组件的内容,并将其发送到我的PUT路径,以便在数据库中进行更新。如果我将console.log数据记录在“saveOverTemplate”方法中,它与预期完全一样。当我单击按钮时,第一个console.log显示我确实找到了方法。但是,当我尝试记录数据时,它只显示为“未定义”。有人能看出我在如何发送数据时遗漏了什么吗

//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;

使用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));
    }
文件:

谢谢。我加了这些,得到了同样的结果。但当我简单地添加app.use(bodyParser.json())时,它就开始工作了。我不敢相信事情竟那么简单。
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));
    }