数据未正确发送到后端

时间:2018-08-13 14:21:47

标签: node.js reactjs

我正在使用react和nodejs作为后端,后端工作正常,我想当我在邮递员中尝试时,但是当尝试连接到我的前端时,它没有正确插入

这是React应用中的代码

class CreateChapter extends React.Component {
    constructor(props){
      super(props);
      this.state={
        // editorState: EditorState.createWithContent(convertFromRaw(JSON.parse(content))),
        titleChapter: "",
        editorState: EditorState.createEmpty(),
        id: this.props.location.state.id,
        status: '',
        errorSaving: '',
        saved: false
      }
    }

    // handle editor change
    onEditorStateChange = (editorState) => {
        this.setState({ editorState })
    }

    //handle title change
    onTitleChange = (event) => {
        this.setState({
            titleChapter: event.target.value
        })
    }

    //load data chapter saved
    loadChapterSaved = (data) => {
        this.setState({
            titleChapter: data.titleChapter,
            editorState: data.editorState,
            status: 'saved'
        })
    }

    //load data chapter published
    loadChapterPublished = (data) => {
        this.setState({
            titleChapter: data.titleChapter,
            editorState: data.editorState,
            status: 'published'
        })
    }

    //save data
    onSaveData = () => {
        const convertedData = convertToRaw(this.state.editorState.getCurrentContent());
        fetch('http://localhost:3001/new-chapter',{
            method: 'post',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                id: this.state.id,
                editorState: convertedData,
                titleChapter: this.state.titleChapter,
                status: this.state.status                 
            })
        })
        .then(response => response.json())
        .then( chapter => {
            console.log(chapter)
            if(chapter === 'empty input'){
                this.setState({
                    errorSaving: 'Please fill Title Chapter and the Content'
                })
            }else{
                this.loadChapterSaved(chapter);
            }
        })
    }

    render() {
        const { classes, ...rest } = this.props;
        const {editorState, id, errorSaving, saved} = this.state;

        console.log('status', this.state.status)
        return (
          <div>
            <HeaderHome/>
            <div className={classNames(classes.main, classes.mainRaised)}>
              <div className={classes.container}>
                <div className={classes.storymargin}>
                <h2 className={classes.title}>New Chapter</h2>
                <Card className={classes.chaptercontainer}>
                    <CardContent>
                        <TextField 
                            fullWidth
                            label=" New Chapter Title"
                            id="chapter-title"
                            onChange={this.onTitleChange}
                            InputProps={{
                                disableUnderline: true,
                                classes:{
                                    input: classes.titleinput
                                }
                            }}
                            InputLabelProps={{
                                shrink: true,
                                className: classes.titleformlabel
                            }}
                            margin="normal"
                        />

                    <Editor 
                        editorState={editorState}
                        wrapperClassName={classes.homewrapper}
                        editorClassName={classes.homeeditor}
                        toolbarClassName={classes.toolbar}
                        placeholder="Begin typing..."
                        onEditorStateChange={this.onEditorStateChange}                 
                    />
                    </CardContent>
                    {errorSaving ? 
                            <div className={classes.errorSavingChap}>
                                {errorSaving}
                            </div>
                            : 
                            ""
                        }
                    <CardActions className={classes.displaybutton}>
                        <Button size="small" clor="primary" className={classes.buttonnextchap}
                        onClick={this.onSaveData}>
                            Save
                        </Button>
                        <Button size="small" clor="primary" className={classes.buttonnextchap}
                        onClick={this.onPublishData}>
                            Publish
                        </Button>
                    </CardActions>
                </Card>
                </div> 
              </div>
            </div>
            <div className={classes.footer}>
              <Footer />
            </div>
          </div>
        );
      } }

export default withStyles(createStoryStyle)(CreateChapter);

问题是this.state.status没有正确发送到后端,它始终接收初始状态,该状态为null。我认为这与setState的异步方式有关,但我不太确定。当我在邮递员中尝试过时,它确实起作用。

这是我的后端

app.post('/new-chapter', (req, res) => {
    const { id, titleChapter, editorState, status } = req.body;
    if(titleChapter === '' || editorState === ''){
        db('story').where('id_user', '=', id)
            .increment('chapter', 0)
            .returning('chapter')
            .then( chapter => { 
                res.json('empty input')
            })
            .catch( err => res.json('cannot add chapter'))
    }else{
        db('story').where('id_user', '=', id)
            .increment('chapter', 1)
            .returning('chapter')
            .then( chapter => {
                db.select('entry').from('story').where('id_user', '=',id)
                .then( newChap => {
                    const chapterEntry = newChap[newChap.length - 1].entry;
                    db('chapter').where('id_user', '=', id)
                    .returning('*')
                    .insert({
                        chapter: chapter[0],
                        titlechapter: titleChapter,
                        content: editorState,
                        id_user: id, 
                        status: status,
                        entry: chapterEntry,
                    })
                    .then( newChapter => {
                        res.json(newChapter[0])
                    })
                    .catch( err => res.json('cannot add new chapter'))
                } 
                ) 
            })
            .catch( err => res.json('cannot add new chapter'))
    }
})

0 个答案:

没有答案
相关问题