【问题标题】:Axios code not running after `.then`在`.then`之后没有运行Axios代码
【发布时间】:2019-01-12 08:45:35
【问题描述】:

我是react/nodejs/express/javascript的新手,遇到了以下问题:

我想获取一个数字,然后发布该数字 + 1,然后我想使用该数字创建一个新的 js 对象(newFreshId),我想添加它以将该事件添加到我的schedulerData。当我尝试运行代码时,我可以获取并发布到/api/num,但是.then(function(response) { 之后的所有内容似乎都没有运行。

我想按顺序执行此操作,所以我在每个任务后使用.then,这样我就不会遇到问题了。

我还尝试删除所有 .thens 以支持等待值更改的 while 循环。这也没有奏效。

代码:

客户:

this.newEvent = (schedulerData, slotId, slotName, start, end, type, item) => {
    let newFreshId = 0;
    let newEvent = {}
    axios.get("/api/num").then(function(response) {
        newFreshId = response.data[0] + 1;

        // console.log(newFreshId);
    }).then(function() {
        axios.post("/api/num", {
            id: newFreshId
        }).then(function(response) {
            console.log(response)
            // handle success
            newEvent = {
                id: newFreshId,
                title: this.state.title,
                start: start,
                end: end,
                resourceId: slotId
            };
            schedulerData.addEvent(newEvent);
            this.setState({
                viewModel: schedulerData
            });

            // while(JSON.stringify(newEvent) === '{}'){
            //   console.log('waiting')
            // }

            console.log(newEvent)
            schedulerData.addEvent(newEvent);

            console.log(newEvent)
            this.setState({
                viewModel: schedulerData
            });
        })
    })
};

服务器:

app.get('/api/num', function(req, res) {
    //console.log(require('./number.json'))
    var fs  = require('fs')
    fs.readFile('./number.json', {encoding:   'utf-8'}, function(err,data){
    if (!err) {
        //console.log('received data: ' + JSON.parse(data));
        res.json(JSON.parse(data))
    } else {
        console.log(err);
    }})
})

app.post('/api/num', function(req, res) {
    var id = req.body.id
    var fs = require('fs');

    fs.writeFileSync("./number.json", "[ "+id+" ]", function(err) {
        if(err) {
            return console.log(err);
        }
        res.status(200)
    })
})

感谢大家的帮助:)

【问题讨论】:

  • 尝试添加catch 看看是否有任何错误。
  • 这可能是一个愚蠢的问题,但我该把问题放在哪里呢?在服务器还是客户端?
  • 在你的.thens之后
  • 没有错误...运行良好
  • 有同样的问题。

标签: javascript node.js reactjs express axios


【解决方案1】:

fs.writeFileSync 没有回调,因此您添加的函数永远不会被执行:https://nodejs.org/api/fs.html#fs_fs_writefilesync_file_data_options

这意味着永远不会将响应发送回客户端,并且永远不会解析 axios 承诺。

尝试使用带有回调的fs.writeFilehttps://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback

在出现错误时发送响应也是一个好主意。

app.post('/api/num', function(req, res) {
    var id = req.body.id
    var fs = require('fs');

    fs.writeFile("./number.json", "[ "+id+" ]", function(err) {
        if(err) {
            console.log(err);
            return res.status(200)
        }
        res.status(200)
    })
})

最后,虽然它在这种情况下对您没有帮助,但您应该在 axios 链的最末端添加一个 .catch。承诺链中发生的任何错误都将在那里结束。

一个例子:

axios.get(specs).then(someFunction).catch(e => console.error(e));

【讨论】:

  • 感谢您的帮助,但没有成功。我将尝试不带回调的 fs.writeFileSync,也许这会起作用
  • 酷酷。请务必检查您的控制台是否有浏览器中的错误,并添加 catch
  • 我会区分您的 api 端点('/api/num1''/api/num2'),并在开头放置一个控制台日志,以确保命中正确的日志。你确定执行甚至到达fs.writeFileSync?顺便说一句,在现实世界中,您可能实际上并不想在编写文件时阻止响应。这对于测试来说很好,但我会立即在您的应用程序中做出响应,然后在 res.status(200) 之后异步写入文件。
  • 好的,现在我收到 500 错误。 Error: "Request failed with status code 500"这是回复Proxy error: Could not proxy request /api/nump from localhost:3000 to http://localhost:3001 (ECONNRESET).
【解决方案2】:

对我来说,我遇到了同样的问题,我发现这是因为我在发出发布请求后使用了一些重定向

window.location.href = "/{redirect to some rout}"

这会使控制台立即更改,因此除非我删除重定向,否则我看不到 then 响应。

【讨论】:

    【解决方案3】:

    我也遇到了无法运行 .then() 或 .catch() 代码的问题

    const fetch = async() => {
      axios.get("https://jsonplaceholder.typicode.com/todos/1")
        .then((res) => {
          console.log(res)
        })
        .catch(err => {
          console.log(err)
        })
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.24.0/axios.min.js"></script>
    我所做的只是将 async 添加到函数中,然后它就开始工作了

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-29
      • 2021-08-03
      • 2019-12-03
      • 1970-01-01
      • 2023-02-07
      • 2021-06-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多