首页 > 解决方案 > 节点中的请求有效,但在 js(vue)中无效

问题描述

嗨,我有一个后端,它收到带有图片和存储的请求,我用邮递员和下面的代码试了一下,效果很好

var axios = require('axios')
var FormData = require('form-data')
var fs = require('fs')
var data = new FormData()
data.append('file', fs.createReadStream('index.png'))
console.log('HEADERS')
console.log(data.getHeaders())
let config = {
  method: 'post',
  url: 'http://localhost:5013/v1/business/honda/widget/test/',
  headers: {
    ...data.getHeaders(),
  },
  data: data,
}

问题出在我的 vue 应用程序中,我尝试使用下一个代码来执行此操作,我有 2 个按钮,一个用于加载图像,另一个用于发送图像。在后端尝试选择“文件”时出现以下错误

http:没有这样的文件

 let imageData
//send the image to backend
    function funtest() {
      console.log('image')

      const formData = new FormData()
      const url = 'http://localhost:5013/v1/business/honda/widget/test/'

      formData.append('file', imageData)
      let config = {
        method: 'post',
        url: url,
        headers: {
          'Content-type': 'multipart/form-data',
        },
        data: formData,
      }
      axios(config)
        .then((response) => {
          console.log('RESPONSE')
          console.log(response)
        })
        .catch((error) => {
          console.log('ERROR')
          console.log(error)
        })
    }

//function to read the image 
    function onImage(data) {
      const reader = new FileReader()
      reader.onload = (e) => {
        imageData = e.target.result
        console.log('imagen')
      }
      reader.readAsDataURL(data.target.files[0])
    }

标签: javascriptapivue.js

解决方案


我认为这里可能没有index.png正确读取文件的路径,fs.createReadStream('index.png')

考虑path像这样使用

const path = require('path');

const filePath = path.join(__dirname,  'index.png');

data.append('file', fs.createReadStream(filePath))

注意:这只是一个快速而肮脏的建议,不能保证有效,但绝对值得一试


推荐阅读