【问题标题】:Axios post isn't handling the responseAxios 帖子未处理响应
【发布时间】:2019-06-18 06:55:03
【问题描述】:

我正在将图像上传到 Cloudinary,并希望在上传后检索图像 url。它正在正确上传,我可以控制台记录服务器端的 url,但之后客户端的 axios 调用中没有处理响应,并且没有出现错误消息。

我的客户:

submitFile = () => {
    var formData = new FormData();
    formData.append('image', this.state.file, 'tmp_name');//this.state.file is not correct format compared to postman constructed
    axios.post('http://localhost:3000/upload', formData).then(function(response) {
      console.log(response);
    });
  }

我的服务器:

  server.post('/upload', async (req, res, next) => {
    const upload = multer({ storage }).single('image')
    upload(req, res, function(err) {
      if (err) {
        return res.send(err)
      }
      const path = req.file.path
      cloudinary.uploader.upload(
        path,
        { public_id: `${filename()}` },
        async function(err, image) {
          if (err) return res.send(err)
          console.log('file uploaded to Cloudinary')
          // remove file from server
          const fs = require('fs')
          fs.unlinkSync(path)
        }
      ).then(result => {res.send(result)})
    })

再次,我希望能够查看响应并保存它,但之后的所有内容.then 都不会执行。

【问题讨论】:

    标签: node.js reactjs express axios


    【解决方案1】:

    您需要删除服务器代码中的括号

    server.post('/upload', async (req, res, next) => {
        /* upload code*/
          ).then(result => res.send(result))
        })
    

    或 在服务器代码的 then 中添加返回

    server.post('/upload', async (req, res, next) => {
        /*upload code*/
              ).then(result => { return res.send(result)})
            })
    

    【讨论】:

    • 对不起,我重读了我的问题,发现我指的是哪个 .then 块模棱两可。我试图在前端代码中记录对控制台的响应,以确保我收到了正确的 url 以保存到数据库,但它似乎没有运行。因此,为了澄清我试图找出的问题在于 axios.post 行。
    猜你喜欢
    • 2018-03-17
    • 2022-01-10
    • 2021-05-22
    • 2020-07-09
    • 1970-01-01
    • 2021-01-25
    • 2011-07-30
    • 1970-01-01
    相关资源
    最近更新 更多