nodejs react js将图像发送到后端

时间:2019-12-08 02:03:50

标签: node.js reactjs

您好,我有一种在添加图片的地方添加商品的方法

async addProduct(req, res) {
    const { filename } = req.file;
    const {name,float,price,description,subcategory_id,exterior_id,type_id} = req.body
    const subcategory = await SubCategory.findByPk(subcategory_id);
    if(!subcategory){ return res.status(400).json({error: 'SubCategory not found'})}
    const exterior = await Exteriors.findByPk(exterior_id);
    if(!exterior){ return res.status(400).json({error: 'Exterior not found'})}
    const types = await Types.findByPk(type_id);
    if(!types){ return res.status(400).json({error: 'Type not found'})}

    const product = await Products.create({subcategory_id,exterior_id,type_id,name,float,price, img_product: filename, description});
    if(product){ return res.status(201).json(product)}
    else{return res.status(400).json({result: 'Failed to create Product'})}  
}

我有一条从我的后端获取所有产品的途径:

async getAllProduct(req,res){
    try {
        const results = await Products.findAll({
            // raw: true, <= remove
            attributes:['id','name', 'float', 'price','img_product', 'description'],
            include: [{
                model: SubCategory,
                as: 'subcategory',
                attributes: ['id','name'],
            },
            {
                model:Exteriors,
                as: 'exteriors',
                attributes: ['id','name']
            },
            {
                model:Types,
                as: 'types',
                attributes: ['id','name']
            },
        ],
        })

        let listProducts= results.map( (products) => {
            return {
                id: products.id,
                name: products.name,
                float: products.float,
                price: products.price,
                id_sub: products.subcategory.id,
                subcategory: products.subcategory.name,
                id_types: products.types.id,
                type: products.types.name,
                id_ext: products.exteriors.id,
                exterior: products.exteriors.name,
                img: products.img_product,
                description: products.description
            }
        })

        const fn = listProducts.filter(v => v.id_ext == 2)
        const mw = listProducts.filter(v => v.id_ext == 3)
        const ft = listProducts.filter(v => v.id_ext == 1)
        const ww = listProducts.filter(v => v.id_ext == 4)
        const bs = listProducts.filter(v => v.id_ext == 5)

        if(listProducts){return res.status(200).json({listProducts,fn,mw,ft,ww,bs})}
        else{return res.status(400).json({result: 'failed to get Products'})}
     } catch (error) {
         console.error(error);
     }
},

但是然后我需要为图像网址创建路由 以便根据您的ID显示在前端 但我不知道该怎么做

在猫鼬中,我可以做类似的事情:

  

ProductS schema.virtual()。取得(function(){返回网址   {product_img}}

但是我不知道如何做续集 基本上,我需要将图像上传到前端。 有人可以给我一些入门方面的帮助吗?

0 个答案:

没有答案