繁体   English   中英

等待 axios 后调用后的代码未运行,catch 块中没有错误

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

我无法弄清楚为什么这行之后的代码没有运行:

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

评论在后端创建并保存到数据库中。 服务器端代码有效,我在 Postman 中对其进行了测试,我得到了正确的响应。 我在前端的捕获中没有收到错误。 请帮忙。

客户

创建评论.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);
        }
    };

服务器

评论.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"}

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

axios请求是在此处提交表单事件时提出的。 提交的默认行为是提交表单并导航到新的 URL,这会导致浏览器中止请求,因为它假定不再需要该请求。 添加e.preventDefault(); 事件处理程序将解决此问题,这是一个工作示例:

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

暂无
暂无

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

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