首页 > 解决方案 > Cloudinary 上传图像不起作用(反应本机和节点

问题描述

我正在尝试将我的 react 本机应用程序中的图像上传到 nodejs 和 cloudinary 云,但它对我不起作用。那是我的反应原生代码:

const App = () => {
  const [profileImageSource ,setProfileImageSource] = useState(require('./images/profilePic.png'));
  const [imageData, setImageData] = useState("");
  const [okay, setOkay] = useState(false);

  const config = {
    withCredentials: true,
    baseURL: 'http://localhost:3000/',
    headers: {
      "Content-Type": "application/json",
    },
  };
  const handleProfileImage = () => {
      const options = {
        title: 'Select photo',
        base64: true
      };

      ImagePicker.showImagePicker(options, (res) => {
        if(res.didCancel){
        }
        else if(res.error){
        }
        else{
          const image = {data: res.data};

          axios
          .post('/clients/upload-image', {
            data: JSON.stringify({image})
          },
          config
        )
          .then((res) => console.log("ok"))
          .catch((err) => alert(err));
        }
      })
    }

这就是我的nodejs代码:

require('dotenv').config();

const cloudinary = require('cloudinary').v2;

//Cloudinary configurations
cloudinary.config({
    cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
    api_key: process.env.CLOUDINARY_API_KEY,
    api_secret: process.env.CLOUDINARY_API_SECRET
});

app.post('/clients/upload-image', (req, res) => {
    const imageStr = req.body.data;
    const uploadedResponse = 
        cloudinary
        .uploader
        .upload(imageStr, {
            upload_preset: 'user',
        })
        .then((uploadedResponse) => console.log(uploadedResponse))
        .catch((err) => console.log("error"));
}

我哪里错了?我不断收到错误,图片没有上传到云端

标签: node.jsreact-nativecloudinaryreact-native-image-picker

解决方案


你能分享你收到的错误信息吗?另外,您能否确认imageStr(aka req.body.data) 在后端被正确接收?(也许在上传之前打印它?)


推荐阅读