javascript - 节点中的请求有效,但在 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])
}
解决方案
我认为这里可能没有index.png
正确读取文件的路径,fs.createReadStream('index.png')
考虑path
像这样使用
const path = require('path');
const filePath = path.join(__dirname, 'index.png');
data.append('file', fs.createReadStream(filePath))
注意:这只是一个快速而肮脏的建议,不能保证有效,但绝对值得一试
推荐阅读
- python - 如何在烧瓶中制作具有特定文章ID的标签列表?
- android - Hilt UninitializedPropertyAccessException 试图注入 SipManager
- python - 增强图像不存储在它们自己的类目录中
- javascript - d3.js 条形图:从可观察到常规 js
- ios - Alamofire 错误:“结果”类型的值
'没有成员'值' - ruby-on-rails - 按批次 ID 搜索 Rails Redis
- python - 为什么在安装 slycot 时出现此 CMAKE_C_COMPILER 错误?
- apache-spark - PySpark:检查 col 中的值是否类似于 dict 中的键
- ruby-on-rails - 如何在 Rails 的弹性搜索客户端中创建动态 ID?
- docker - curl 在 gitlab-ci 运行器上超时失败