How to solve this error: TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received undefined

286 views Asked by At

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received undefined at new NodeError (node:internal/errors:399:5) at validateString (node:internal/validators:163:11) at Object.extname (node:path:1386:5) at /home/stephennwac/Downloads/node_file_uploader/middleware/fileExtLimiter.js:9:38 at Array.forEach () at /home/stephennwac/Downloads/node_file_uploader/middleware/fileExtLimiter.js:8:28 at Layer.handle [as handle_request] (/home/stephennwac/Downloads/node_file_uploader/node_modules/express/lib/router/layer.js:95:5) at next (/home/stephennwac/Downloads/node_file_uploader/node_modules/express/lib/router/route.js:144:13) at filesPayloadExists (/home/stephennwac/Downloads/node_file_uploader/middleware/filesPayloadExists.js:4:5) at Layer.handle [as handle_request] (/home/stephennwac/Downloads/node_file_uploader/node_modules/express/lib/router/layer.js:95:5)

I tried to get the result of the object by returning it but i keep getting this error. Here are my snippets.

here is the app.js file

const express = require("express");
const fileUpload = require("express-fileupload");
const path = require("path");

const filesPayloadExists = require('./middleware/filesPayloadExists');
const fileExtLimiter = require('./middleware/fileExtLimiter');
const fileSizeLimiter = require('./middleware/fileSizeLimiter');

const PORT = process.env.PORT || 3800;

const app = express();

app.get("/", (req, res) => {
    res.sendFile(path.join(__dirname, "index.html"));
});

app.post('/upload',
    fileUpload({ createParentPath: true }),
    filesPayloadExists,
    fileExtLimiter(['.png', '.jpg', '.jpeg']),
    fileSizeLimiter,
    (req, res) => {
        const files = req.files
        console.log(files)

        Object.keys(files).forEach(key => {
            const filepath = path.join(__dirname, 'files', files[key].name)
            files[key].mv(filepath, (err) => {
                if (err) return res.status(500).json({ status: "error", message: err })
            })
        })

        return res.json({ status: 'success', message: Object.keys(files).toString() })
    }
)




app.listen(PORT, () => console.log(`Server running on port ${PORT}`));


Here is the index.html file

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Node.js File Uploader</title>
    <style>
        body {
            font-family: Arial, Helvetica, sans-serif;
            font-size: 1.5rem;
            background-color: #333;
            color: whitesmoke;
        }

        input,
        button {
            font: inherit;
            width: max-content;
        }

        form {
            display: flex;
            flex-flow: column nowrap;
            gap: 1.5rem;
        }
    </style>
</head>

<body>
    <h1>Node.js File Uploader</h1>
    <form id="uploadForm">
        <input type="file" id="myFiles" accept="image/*" multiple />
        <button>Submit</button>
    </form>
    <h2></h2>
    <h3></h3>
    <script>
        const form = document.getElementById('uploadForm')

        const sendFiles = async () => {
            // Object 
            const myFiles = document.getElementById('myFiles').files

            const formData = new FormData()

            Object.keys(myFiles).forEach(key => {
                formData.append(myFiles.item(key).name, myFiles.item(key))
            })

            const response = await fetch('http://localhost:3500/upload', {
                method: 'POST',
                body: formData
            })

            const json = await response.json()

            const h2 = document.querySelector('h2')
            h2.textContent = `Status: ${json?.status}`

            const h3 = document.querySelector('h3')
            h3.textContent = json?.message

            console.log(json)
        }

        form.addEventListener('submit', (e) => {
            e.preventDefault()
            sendFiles()
        })
    </script>
</body>

</html>

here is the package.json file showing the dependencies

{
  "name": "node_file_uploader",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "start": "node app.js",
    "dev": "nodemon app.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.1",
    "express-fileupload": "^1.4.0"
  },
  "devDependencies": {
    "nodemon": "^2.0.16"
  }
}
0

There are 0 answers