【问题标题】:My request works in Postman ut not in browser (React, Node, Cloudinary)我的请求在 Postman 中有效,但在浏览器中无效(React、Node、Cloudinary)
【发布时间】:2021-11-12 06:31:44
【问题描述】:

我有一个页面,我在 NodeJs + MongoDb 中创建了后端,并在 React 中创建了前端。在后端,我有一个中间件,用于将图像上传到 Cloudinary。例如,一条路线是创建一个新宠物,当我使用 Postman 进行发布请求时,一切顺利,新宠物在数据库中创建得很好,并且在图像位置也有 Cloudinary 的 URL。当我尝试对反应中的表单执行相同操作时,问题就来了……一切都“很好”,但是在图像位置(邮递员在哪里我有 clodinary url),现在是空的……

节点控制器代码:

const petCreatePost = async(req, res, next) => {
    const { type, name, avatar, age, sex, breed, size, isVaccinated, isSterilized, isDewormed, microchip, province, shelter, status } = req.body;

    try {

        const newPet = new Pet({
            type,
            name,
            avatar: req.imageUrl ? req.imageUrl : '',
            age,
            sex,
            breed,
            size,
            isVaccinated,
            isSterilized,
            isDewormed,
            microchip,
            province,
            shelter,
            status
        });

        const createdPet = await newPet.save();

        return res.status(200).json('Mascota creada correctamente', { pet: createdPet });
    } catch (error) {
        return next(error);
    }

}

云中间件:

const multer = require('multer');
const path = require('path');
const fs = require('fs');
const cloudinary = require('cloudinary').v2

const ACCEPTED_FILE = [ 'image/jpg', 'image/jpeg', 'image/png' ];

const fileFilter = (req, file, cb) => {
    if(!ACCEPTED_FILE.includes(file.mimetype)) {
        const error = new Error ('Extensión del archivo inválida.')
        error.status = 400;
        return cb(error);
    }
    return cb(null, true);
};

const storage = multer.diskStorage({
    filename: (req, file, cb) => {
        const fileName = `${Date.now()}-${file.originalname}`;
        cb(null, fileName);
    },
    destination: (req, file, cb) => {
        const directory = path.join(__dirname, '../public/uploads');
        cb(null, directory);
    }
});

const upload = multer({
    storage,
    fileFilter,
});

const uploadToCloudinary = async (req, res, next) => {
    try {
        console.log('req', req);
        if(req.file) {
            const path = req.file.path;
            const image = await cloudinary.uploader.upload(path);
    
            req.imageUrl = image.secure_url;
            console.log('image url', req.imageUrl);
    
            return next();
        } else {
            return next();
        }
    } catch (error) {
        return next(error);
    }
};

module.exports = { upload, uploadToCloudinary };

我如何使用中间件:

router.post('/new', [upload.single('avatar'), uploadToCloudinary], controller.petCreatePost);

反应组件:

import React, { useContext } from 'react';

export const NewPet = () => {

  const submitForm = async (e) => {
    e.preventDefault();

    const { type, name, age, avatar, sex, breed, size, isVaccinated, isSterilized, isDewormed, microchip, province, status } = e.target;

    const form = {
      type: type.value,
      name: name.value,
      age: age.value,
      sex: sex.value,
      breed: breed.value,
      size: size.value,
      isVaccinated: isVaccinated.value,
      isSterilized: isSterilized.value,
      isDewormed: isDewormed.value,
      microchip: microchip.value,
      province: province.value,
      status: status.value
    };

    // const form = new FormData();
    // form.append('type', type.value);
    // form.append('name', name.value);
    // form.append('age', age.value);
    // form.append('sex', sex.value);
    // form.append('breed', breed.value);
    // form.append('size', size.value);
    // form.append('isVaccinated', isVaccinated.value);
    // form.append('isSterilized', isSterilized.value);
    // form.append('isDewormed', isDewormed.value);
    // form.append('microchip', microchip.value);
    // form.append('province', province.value);
    // form.append('status', status.value);
    // form.append('avatar', imagenPrueba);

    try {
      const pet = await newPet(form);
      console.log('pet', pet);

    } catch (err) {
      console.log(err);
    }
  }

注释的代码部分是我尝试使用的替代方法,因为我正在发送文件并且我必须使用 FormData,但也无法正常工作。我还检查了表单是否具有 enctype="multipart/form-data"。

最后是我用来连接到后面的“newPet”功能:

export const newPet = async(form) => {
    const req = await fetch(newPetUrl, {
        method: "POST",
        headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
            "Access-Control-Allow-Origin": "*",
        },
        credentials: "include",
        body: JSON.stringify(form),
    });

    const response = await req.json(form);

    if (!req.ok) {
        throw new Error(response.message);
    }

    return response;
};

我希望有人可以帮助我.. 谢谢!

【问题讨论】:

    标签: javascript node.js reactjs mongodb cloudinary


    【解决方案1】:

    您需要等待来自 cloudinary 的网址。我也有这个问题

    【讨论】:

    • 你到底是什么意思?在我发布图片的中间件中,我正在等待响应:``` const image = await cloudinary.uploader.upload(path); ```
    • 在请求后立即尝试控制台日志
    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    • 我发现中间件中的 req.file 是未定义的......我认为问题是当我向后面发出请求时,图像文件没有与其余参数一起使用.如果我尝试我发布的代码,一切顺利,但图像没有到达后面......这就是我尝试使用 FormData 的原因,因为我正在发送文件,但如果我尝试完全使用 FormData就像我在示例中那样,在我的后面我在控制台中有一个错误,说某些参数是必需的,我没有发送它,暗示信息没有正确到达..
    猜你喜欢
    • 2016-07-11
    • 2020-07-31
    • 2018-06-30
    • 2022-10-31
    • 1970-01-01
    • 2021-03-24
    • 1970-01-01
    • 1970-01-01
    • 2016-10-25
    相关资源
    最近更新 更多