简体   繁体   中英

code after await axios post call is not running, no error in catch block

I cannot figure out why the code after this line does not run:

const res = await axios.post('http://localhost:4000/api/v1/comment', {
                content,
            });

The comment gets created on the backend and saved to the database. The server side code works, I tested it in Postman and I get the correct response. I am not getting an error in the catch on the frontend. Help please.

CLIENT

CreateComment.js

        try {
            const res = await axios.post('http://localhost:4000/api/v1/comment', {
                content,
            });
            //after this line does not run
            //comment is successfully saved to database
            console.log(res.body);
            props.history.push(`/comment/${res.body.id}`);
        } catch (err) {
            console.error(err);
        }
    };

SERVER

comment.js (controller)

const create = async (req, res) => {
        try {

            const newComment = await Comment.create({
                content: req.body.content,
            });

            return res.send(newComment);
        } catch (e) {
            console.error(e);
            return res.status(400).send(e);
        }
}

EDIT:

response body in Postman:

{"id":34,"content":"happy tuesday","tone":"joy","updatedAt":"2021-04-01T16:06:07.333Z","createdAt":"2021-04-01T16:06:07.333Z"}

CreateComment.js (full component)

import React, { useState } from 'react';
import { withRouter } from 'react-router-dom';
import axios from 'axios';

function CreateComment(props) {
    const [content, setContent] = useState('');

    const handleSubmit = async () => {
        try {
            const res = await axios.post('http://localhost:4000/api/v1/comment', 
            {
                content,
            });
            debugger;
            console.log(res);
            return props.history.push(`/comment/${res.data.id}`);
        } catch (err) {
            console.error(err);
        }
    };

    return (
        <div className='form'>
            <form onSubmit={() => handleSubmit()}>
                <div className='form-input'>
                    {/* Controlled Input */}
                    <input
                        type='text'
                        name='content'
                        onChange={e => setContent(e.target.value)}
                        value={content}
                        className='inputForm'
                    />
                </div>
                <input type='submit' value='Curate' className='button' />
            </form>
        </div>
    );
}

export default withRouter(CreateComment);

The axios request is made on submit event of a form here. The default behavior on submit is to submit the form and navigate to a new URL, this results in the browser aborting the request as it assumes the request is no longer needed. Adding e.preventDefault(); to the event handler will fix this, here is a working example:

https://codesandbox.io/s/react-router-playground-forked-s9op7?file=/index.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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