await axios post调用后的代码没有运行,catch块中没有错误

jhdbpxl9  于 2023-11-18  发布在  iOS
关注(0)|答案(1)|浏览(118)

我不明白为什么这行后面的代码不能运行:

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

字符串
评论在后端创建并保存到数据库。服务器端代码工作,我在Postman中测试了它,我得到了正确的响应。我在前端的catch中没有错误。请帮助。
客户端
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);
        }
    };


服务器
comment.js(控制器)

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


编辑:
Postman中的响应主体:

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


Comment.js(完整组件)

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

m4pnthwp

m4pnthwp1#

axios请求是在表单的submit事件上发出的。submit的默认行为是提交表单并导航到新的URL,这会导致浏览器中止请求,因为它认为不再需要请求。将e.preventDefault();添加到事件处理程序将解决这个问题,这里是一个工作示例:
https://codesandbox.io/s/react-router-playground-forked-s9op7?file=/index.js

相关问题