【问题标题】:code after await axios post call is not running, no error in catch blockawait axios post 调用后的代码未运行,catch 块中没有错误
【发布时间】:2021-06-28 18:45:23
【问题描述】:

我不知道为什么这行之后的代码没有运行:

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

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

客户

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"}

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

【问题讨论】:

  • 你能显示res的console.log输出吗?还是 Postman 输出或屏幕截图?
  • 在你的服务器文件中尝试返回return res.status(201).send(newComment);
  • @BikkiMahato 我添加了邮递员响应正文。 console.log(res.body) 没有运行,history.push() 我也没有改为:return res.status(201).send(newComment); 但我仍然遇到同样的问题。
  • 你可以尝试在你的axios调用中添加适当的标题,有时是与标题相关的问题。
  • 当我运行前端代码时,评论被创建并保存到数据库中。

标签: javascript reactjs async-await promise axios


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2019-08-05
    • 2019-01-12
    • 2014-12-15
    • 2018-03-04
    • 2019-07-04
    • 2019-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多