有什么方法可以将一条路线的结果作为另一条路线中的字段传递?

时间:2019-07-10 11:01:29

标签: javascript express multer cloudinary

我正在尝试将带有multer的图像上传到cloudinary,然后将生成的url存储在数据库列中。我有以下代码:

cloudinary配置文件:

import { config, uploader } from 'cloudinary'
import dotenv from 'dotenv';
dotenv.config();
const cloudinaryConfig = (req, res, next) => {
config({
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET,
});
next();
}
export { cloudinaryConfig, uploader };

multer配置文件:

import multer from 'multer';
import Datauri from 'datauri';
import path from 'path';
const storage = multer.memoryStorage();
const multerUploads = multer({ storage }).single('image');
const dUri = new Datauri();

/**
* @description This function converts the buffer to data url
* @param {Object} req containing the field object
* @returns {String} The data url from the string buffer
*/

const dataUri = req => dUri.format(path.extname(req.file.originalname).toString(), req.file.buffer);
export { multerUploads, dataUri };

入口点文件(app.js)

import express from 'express';
import { urlencoded, json } from 'body-parser';
import { resolve } from  'path';
import { uploader, cloudinaryConfig } from './config/cloudinaryConfig'
import { multerUploads, dataUri } from './middlewares/multerUpload';
const app = express();
const Port = process.env.PORT || 3000;
app.use(express.static(resolve(__dirname, 'src/public')));
app.use(urlencoded({ extended: false }));
app.use(json());
app.use('*', cloudinaryConfig);

**app.post('/upload', multerUploads, (req, res) => {**
if(req.file) {
const file = dataUri(req).content;
return uploader.upload(file).then((result) => {
const image = result.url;
return res.status(200).json({
messge: 'Your image has been uploaded successfully to cloudinary',
data: {
image
}
})
}).catch((err) => res.status(400).json({
messge: 'something went wrong while processing your request',
data: {
err
}
}))
}
});
app.listen(Port, () => console.log(`Server started at http://localhost:${Port}`));

我试图拆分函数并在应用程序路由中调用它们,但是req.file是未定义的,而在其他情况下,则不会生成url并且不会引发任何错误。我还查看了快速文档,以查看是否可以将路线的结果存储在变量中,但是看不到这样写的内容。

carRouter.post('/car', verifyToken, postAdchecker, cloudinaryConfig, multerUploads, postCarAd);

我希望将上传路线的结果(即生成的网址)作为字段(imageurl)传递到另一个 route(postCarAd)。我该如何实现?

0 个答案:

没有答案