Cha*_*Hon 3 javascript post node.js vue.js axios
目前,我正在创建一个包含图像数据和 JSON 数据的表单。我使用 2 post 方法将图像数据和 JSON 数据分别发布到我的 Nodejs 后端。是否有任何可能的解决方案使我能够仅通过使用 axios 和使用 Nodejs 的后端来发布一次图像和 JSON 数据。
以下是我的代码。
前端vue.js
submitAuth() {
console.log(this.promo.bannerImg)
const formData = new FormData()
formData.append('bannerImg', this.promo.bannerImg)
formData.append('inAppImg', this.promo.inAppImg)
formData.append('inAppImg', this.promo)
axios.post(`http://localhost:5000/success`,
this.promo
)
.then(response => {
console.log('Submit Success')
})
.catch(e => {
console.log('Submit Fail')
})
axios.post('http://localhost:5000/uploadImg',
formData
).then(response => {
console.log('Submit Success')
}).catch(e => {
console.log('Submit Fail')
})
},
Run Code Online (Sandbox Code Playgroud)
},
后端node.js
app.post("/success", function (request, response) {
co(function* () {
var promouid = request.body.uid
var filename = __dirname + '/public/promo-json/' + promouid + '.json'
var promotionJSON = JSON.stringify(request.body)
fs.writeFile(filename, promotionJSON, 'utf-8', function (err) {
if (err) throw err;
console.log(request.body);
});
var stream = fs.createReadStream(filename);
var size = fs.statSync(filename).size;
var result = yield client.putStream(
'promojson/' + promouid + '.json', stream, {contentLength: size});
console.log(result);
}).catch(function (err) {
console.log(err);
});
});
app.post("/uploadImg", function (req, res) {
var storage = multer.diskStorage({
destination: 'public/image',
filename: function ( req, file, cb ) {
// set image name
console.log()
cb( null, 'asdasdsad-' + Date.now());
}
});
var upload = multer({
storage: storage,
}).any();
upload(req, res, function(err) {
if (err) {
console.log(err);
return res.end('Error');
} else {
console.log(req.body);
req.files.forEach(function(item) {
console.log(item);
});
res.end('File uploaded');
}
});
});
Run Code Online (Sandbox Code Playgroud)
如果您想使用单个请求上传所有内容,那么您可能最好使用FormData来上传所有需要上传的内容。
您可以获取 JSON 数据,将其序列化为字符串,然后将其与图像一起添加到 FormData 中。
你的前端vue.js看起来像这样:
const formData = new FormData();
// Add images to form data
formData.append('bannerImg', this.promo.bannerImg)
formData.append('inAppImg', this.promo.inAppImg)
formData.append('inAppImg', this.promo)
// Add the serialized JSON data to the formData (not
// sure what your JSON object is called)
formData.append('data', JSON.stringify(this.data));
// Submit the form data
axios.post('http://localhost:5000/uploadImg',
formData
).then(response => {
console.log('Submit Success')
}).catch(e => {
console.log('Submit Fail')
});
Run Code Online (Sandbox Code Playgroud)
在后端,您只需反序列化FormData 中发送到 JSON 对象的数据字段,然后就可以使用它。
| 归档时间: |
|
| 查看次数: |
15058 次 |
| 最近记录: |