LoginSignup
0
0

More than 1 year has passed since last update.

Node.jsのESmodule設定でcloudinary機能が使いたとき import cloudinary from 'cloudinary' 思った通りに機能しない。

Last updated at Posted at 2022-02-13

結論

Node.jsでESmodule設定でもCloudinaryを使用するなら下記のようにCommonjsを使う。
v2がないと駄目っぽい?

app.js
import { createRequire } from 'module';
const require = createRequire(import.meta.url);

...

const cloudinary = require('cloudinary').v2; // ok
// import cloudinary from 'cloudinary' // No

使用方法をちゃんと読みましょう(教訓)

import cloudinary from 'cloudinary' だと機能しない?

機能しないと思います。(私は機能しませんでした。)

やりたいこと

ReactからformDataを使って送ってきた画像をCloudinaryに保存して、画像のURL(path)のみMongoDBに保存。

multer-storage-cloudinaryを使用することで、Cloudinaryに保存することができる。

起きたエラー

下記のupload.array('file')の部分で、Cloudinaryに保存するまでは大丈夫でした。
しかし、upload.array('file')のミドルウェアの後、CreatePostの処理にいってくれませんでした...

route.js

router.post('/', auth, upload.array('file'), createPost);

まとめ

解決策としては、最初に記述したようにV2をrequireするだけでした。
このエラーでかなりの時間を消費したので、誰かの助けになればと思います。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0