expressjs

expressjs

Express.js: the fast, unopinionated, minimalist web framework for node

Member Since 8 years ago

Experience Points
0
follower
Lessons Completed
0
follow
Best Reply Awards
41
repos
Activity
Oct
18
17 hours ago
started
started time in 11 hours ago
Activity icon
fork

Ranganath-MD forked expressjs/expressjs.com

fork time in 11 hours ago
started
started time in 12 hours ago
started
started time in 13 hours ago
Activity icon
issue

fazemodz issue expressjs/cors

fazemodz
fazemodz

i keep getting the same error no matter how i comfigure cors

ive tried loads of configs re-installing the pakage but this error always pops up Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/api/v1/LoginUser/LoginUser. (Reason: CORS request did not succeed). the config im runing atm is origin: 'http://localhost:3000', optionsSuccessStatus: 200

Activity icon
issue

thxmike issue expressjs/cors

thxmike
thxmike

String Array in Response Produces Error in Browser

I am using this package on the server side nodejs middleware in with the following configuration:

{ "origin": ["http://localhost:4200","http://localhost","https://*.somedomain.com","https://anotherdomain.net"] "methods": ["GET", "POST", "PUT", "PATCH", "OPTIONS", "HEAD", "DELETE"], "allowedHeaders": ["Content-Type", "Authorization"], "exposedHeaders": ["Content-Type", "Content-Length", "count"] }

I get the following error when using it in a client application.

Access to XMLHttpRequest at 'https://mycustomapi/api/v1/mappings?page=0&per_page=1' from origin 'http://localhost' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values '["http://localhost:4200","http://localhost","https://*.somedomain.com","https://anotherdomain.net"]', but only one is allowed.

It appears it is not returning the single value from the client but the entire defined array from the server. Is there an additional configuration change I need

Activity icon
issue

UrielAzevedo issue expressjs/multer

UrielAzevedo
UrielAzevedo

Unexpected field error using Fetch API

Im trying to use fetch API to send an image file to the server, but I get an unexpected field error.

server (post request with dataBase insert): ` const multer = require('multer') const storageDir = multer.diskStorage({ destination: (req,file,cb) => { cb(null,'./Paintings_img_storage') }, filename: ((req,file,cb) =>{ cb(null, file.fieldname + '-' + Date.now() + '.jpg') }) }) const upload = multer({ storage: storageDir})

app.post('/', upload.single('picture'), (req, res) => {

const values = [req.body.paintName, req.body.yearPainted, req.body.authorName]
const updateQury =  'INSERT INTO paintings (name, year, authorname) VALUES ($1, $2, $3);'

pool.query(updateQury, values, (err, res) =>{    
    if(err){
        console.log(err)
    }
})

}) `

client: ` const submitHandler = (e) => { e.preventDefault()

    const data = new FormData()
    data.append("file", e.target['picture'].files[0])

    const imgPostRequest = {
        method: "POST",
        body: data
    }

    fetch('http://localhost:5504/', imgPostRequest)
    .catch((err) =>{
        console.log(err)
    })

}

`

react jsx html (whole form with other inputs, I'm trying to fetch just the name="picture" input): `

Paint

        <div className="dataContainer">
            <div className="pictureMinuatureContainer">
                <img src={img.file} className="picturePreview" alt=""/>
            </div>
            <div className="atributesContainer">
                <form onSubmit={submitHandler} className="formContainer" method="post" encType="multipart/form-data">
                    <label className="labelContainer">
                        Paint Picture
                        <input type="file" placeholder="Paint Name" className="imputData" name="picture" onChange={imageOnclick} />
                    </label>
                    <label className="labelContainer">
                        <div> Paint Name </div>
                        <input type="text" placeholder="Paint Name" className="imputData" name="paintName" required="required" />
                    </label>
                    <label className="labelContainer">
                        Year Painted
                        <input type="text" placeholder="Year Painted" className="imputData" name="yearPainted" />
                    </label>
                    <label className="labelContainer">
                        Author Name
                        <input type="text" placeholder="Author Name" className="imputData" name="authorName" />
                    </label>

                    <label className="buttonLabelContainer">
                        Submit
                        <button className="submitButton" type="submit" />
                    </label>
                </form>
            </div>
        </div>
    </Fragment>

`

Activity icon
issue

UrielAzevedo issue expressjs/multer

UrielAzevedo
UrielAzevedo

Unexpected field error using Fetch API

Im trying to use fetch API to send an image file to the server, but I get an unexpected field error.

server (post request with dataBase insert): ` const multer = require('multer') const storageDir = multer.diskStorage({ destination: (req,file,cb) => { cb(null,'./Paintings_img_storage') }, filename: ((req,file,cb) =>{ cb(null, file.fieldname + '-' + Date.now() + '.jpg') }) }) const upload = multer({ storage: storageDir})

app.post('/', upload.single('picture'), (req, res) => {

const values = [req.body.paintName, req.body.yearPainted, req.body.authorName]
const updateQury =  'INSERT INTO paintings (name, year, authorname) VALUES ($1, $2, $3);'

pool.query(updateQury, values, (err, res) =>{    
    if(err){
        console.log(err)
    }
})

}) `

client: ` const submitHandler = (e) => { e.preventDefault()

    const data = new FormData()
    data.append("file", e.target['picture'].files[0])

    const imgPostRequest = {
        method: "POST",
        body: data
    }

    fetch('http://localhost:5504/', imgPostRequest)
    .catch((err) =>{
        console.log(err)
    })

}

`

react jsx html (whole form with other inputs, I'm trying to fetch just the name="picture" input): `

Paint

        <div className="dataContainer">
            <div className="pictureMinuatureContainer">
                <img src={img.file} className="picturePreview" alt=""/>
            </div>
            <div className="atributesContainer">
                <form onSubmit={submitHandler} className="formContainer" method="post" encType="multipart/form-data">
                    <label className="labelContainer">
                        Paint Picture
                        <input type="file" placeholder="Paint Name" className="imputData" name="picture" onChange={imageOnclick} />
                    </label>
                    <label className="labelContainer">
                        <div> Paint Name </div>
                        <input type="text" placeholder="Paint Name" className="imputData" name="paintName" required="required" />
                    </label>
                    <label className="labelContainer">
                        Year Painted
                        <input type="text" placeholder="Year Painted" className="imputData" name="yearPainted" />
                    </label>
                    <label className="labelContainer">
                        Author Name
                        <input type="text" placeholder="Author Name" className="imputData" name="authorName" />
                    </label>

                    <label className="buttonLabelContainer">
                        Submit
                        <button className="submitButton" type="submit" />
                    </label>
                </form>
            </div>
        </div>
    </Fragment>

`

Activity icon
issue

UrielAzevedo issue expressjs/multer

UrielAzevedo
UrielAzevedo

Unexpected field error using Fetch API

Im trying to use fetch API to send an image file to the server, but I get an unexpected field error.

server (post request with dataBase insert): ` const multer = require('multer') const storageDir = multer.diskStorage({ destination: (req,file,cb) => { cb(null,'./Paintings_img_storage') }, filename: ((req,file,cb) =>{ cb(null, file.fieldname + '-' + Date.now() + '.jpg') }) }) const upload = multer({ storage: storageDir})

app.post('/', upload.single('picture'), (req, res) => {

const values = [req.body.paintName, req.body.yearPainted, req.body.authorName]
const updateQury =  'INSERT INTO paintings (name, year, authorname) VALUES ($1, $2, $3);'

pool.query(updateQury, values, (err, res) =>{    
    if(err){
        console.log(err)
    }
})

}) `

client: ` const submitHandler = (e) => { e.preventDefault()

    const data = new FormData()
    data.append("file", e.target['picture'].files[0])

    const imgPostRequest = {
        method: "POST",
        body: data
    }

    fetch('http://localhost:5504/', imgPostRequest)
    .catch((err) =>{
        console.log(err)
    })

}

`

react jsx html (whole form with other inputs, I'm trying to fetch just the name="picture" input): `

Paint

        <div className="dataContainer">
            <div className="pictureMinuatureContainer">
                <img src={img.file} className="picturePreview" alt=""/>
            </div>
            <div className="atributesContainer">
                <form onSubmit={submitHandler} className="formContainer" method="post" encType="multipart/form-data">
                    <label className="labelContainer">
                        Paint Picture
                        <input type="file" placeholder="Paint Name" className="imputData" name="picture" onChange={imageOnclick} />
                    </label>
                    <label className="labelContainer">
                        <div> Paint Name </div>
                        <input type="text" placeholder="Paint Name" className="imputData" name="paintName" required="required" />
                    </label>
                    <label className="labelContainer">
                        Year Painted
                        <input type="text" placeholder="Year Painted" className="imputData" name="yearPainted" />
                    </label>
                    <label className="labelContainer">
                        Author Name
                        <input type="text" placeholder="Author Name" className="imputData" name="authorName" />
                    </label>

                    <label className="buttonLabelContainer">
                        Submit
                        <button className="submitButton" type="submit" />
                    </label>
                </form>
            </div>
        </div>
    </Fragment>

`

started
started time in 16 hours ago
Oct
17
1 day ago
started
started time in 17 hours ago
started
started time in 17 hours ago
started
started time in 17 hours ago
started
started time in 20 hours ago
Activity icon
issue

OmkoBass issue comment expressjs/multer

OmkoBass
OmkoBass

Multer only works with dest

The only way i can get multer to work is with

This gets the image in req.file

const upload = multer({ dest: "uploads/" });

Here's my original code that won't get the image

const postStorage = multer.diskStorage({
  destination: (req, file, cb) => cb(null, `./thoughts`),
  filename: (req, file, cb) => cb(null, `${file.originalname}-${Date.now()}`),
});

const fileFilter = (req, file, cb) => {
  if (file.mimetype === "image/*") {
    cb(null, true);
  } else {
    cb(null, false);
  }
};

const upload = multer({
  storage: postStorage,
  limits: {
    fileSize: 1024 * 1024 * 5,
  },
  fileFilter: fileFilter,
});

It's amazing how a library that once worked is now broken, extremely unreliable. Do you really think only having dest will be good enough for most developers ? This is an embarassement!

OmkoBass
OmkoBass

That's a good question, I'd create an examples dir here on this repo. It would contain a few examples like the ones we did and I'd say Examples: 'link to these examples'.

started
started time in 21 hours ago
started
started time in 21 hours ago
started
started time in 22 hours ago
started
started time in 23 hours ago
started
started time in 1 day ago
started
started time in 1 day ago
started
started time in 1 day ago
started
started time in 1 day ago
started
started time in 1 day ago
Activity icon
issue

LinusU issue comment expressjs/multer

LinusU
LinusU

Multer only works with dest

The only way i can get multer to work is with

This gets the image in req.file

const upload = multer({ dest: "uploads/" });

Here's my original code that won't get the image

const postStorage = multer.diskStorage({
  destination: (req, file, cb) => cb(null, `./thoughts`),
  filename: (req, file, cb) => cb(null, `${file.originalname}-${Date.now()}`),
});

const fileFilter = (req, file, cb) => {
  if (file.mimetype === "image/*") {
    cb(null, true);
  } else {
    cb(null, false);
  }
};

const upload = multer({
  storage: postStorage,
  limits: {
    fileSize: 1024 * 1024 * 5,
  },
  fileFilter: fileFilter,
});

It's amazing how a library that once worked is now broken, extremely unreliable. Do you really think only having dest will be good enough for most developers ? This is an embarassement!

LinusU
LinusU

From the readme:

Note: You are responsible for creating the directory when providing destination as a function.


Most of the people don't know that it will break without permissions [...]

Do you have any suggestion on how we might word that? and where to put it?

Activity icon
issue

OmkoBass issue comment expressjs/multer

OmkoBass
OmkoBass

Multer only works with dest

The only way i can get multer to work is with

This gets the image in req.file

const upload = multer({ dest: "uploads/" });

Here's my original code that won't get the image

const postStorage = multer.diskStorage({
  destination: (req, file, cb) => cb(null, `./thoughts`),
  filename: (req, file, cb) => cb(null, `${file.originalname}-${Date.now()}`),
});

const fileFilter = (req, file, cb) => {
  if (file.mimetype === "image/*") {
    cb(null, true);
  } else {
    cb(null, false);
  }
};

const upload = multer({
  storage: postStorage,
  limits: {
    fileSize: 1024 * 1024 * 5,
  },
  fileFilter: fileFilter,
});

It's amazing how a library that once worked is now broken, extremely unreliable. Do you really think only having dest will be good enough for most developers ? This is an embarassement!

OmkoBass
OmkoBass

That's smart. Thanks 👍

Someone should put an example like in the documentation, there will be way less repeating issues like this and simmilar. Most of the people don't know that it will break without permissions or that the dir won't be created automatically and simmilar.

Activity icon
issue

LinusU issue comment expressjs/multer

LinusU
LinusU

Multer only works with dest

The only way i can get multer to work is with

This gets the image in req.file

const upload = multer({ dest: "uploads/" });

Here's my original code that won't get the image

const postStorage = multer.diskStorage({
  destination: (req, file, cb) => cb(null, `./thoughts`),
  filename: (req, file, cb) => cb(null, `${file.originalname}-${Date.now()}`),
});

const fileFilter = (req, file, cb) => {
  if (file.mimetype === "image/*") {
    cb(null, true);
  } else {
    cb(null, false);
  }
};

const upload = multer({
  storage: postStorage,
  limits: {
    fileSize: 1024 * 1024 * 5,
  },
  fileFilter: fileFilter,
});

It's amazing how a library that once worked is now broken, extremely unreliable. Do you really think only having dest will be good enough for most developers ? This is an embarassement!

LinusU
LinusU

Some suggestions:

  const multer = require("multer");
  const fs = require("fs");
+ const path = require("path");

+ const uploadFolder = path.join(__dirname, 'thoughts')
+
  // Check if the dir you want to place pictures in exists
  // IF YOU GET A PERMISSION DENIED
  // With dest or with diskStorage then you also need to add
  // __dirname here
- if (!fs.existsSync("./thoughts")) {
-   fs.mkdir("./thoughts", (err) => {});
- }
+ fs.mkdirSync(uploadFolder, { recursive: true })
  
  const storage = multer.diskStorage({
    // YOU NEED TO USE THE __dirname, IT WILL NOT WORK WITHOUT IT
-   destination: (req, file, cb) => cb(null, __dirname + `/thoughts`),
+   destination: (req, file, cb) => cb(null, uploadFolder),
    // Always give a UNIQUE filename so that the file is not overwritten
    filename: (req, file, cb) => cb(null, `${Date.now()}-${file.originalname}`),
  });

Activity icon
issue

OmkoBass issue comment expressjs/multer

OmkoBass
OmkoBass

Multer only works with dest

The only way i can get multer to work is with

This gets the image in req.file

const upload = multer({ dest: "uploads/" });

Here's my original code that won't get the image

const postStorage = multer.diskStorage({
  destination: (req, file, cb) => cb(null, `./thoughts`),
  filename: (req, file, cb) => cb(null, `${file.originalname}-${Date.now()}`),
});

const fileFilter = (req, file, cb) => {
  if (file.mimetype === "image/*") {
    cb(null, true);
  } else {
    cb(null, false);
  }
};

const upload = multer({
  storage: postStorage,
  limits: {
    fileSize: 1024 * 1024 * 5,
  },
  fileFilter: fileFilter,
});

It's amazing how a library that once worked is now broken, extremely unreliable. Do you really think only having dest will be good enough for most developers ? This is an embarassement!

OmkoBass
OmkoBass
const multer = require("multer");
const fs = require("fs");

// Check if the dir you want to place pictures in exists
// IF YOU GET A PERMISSION DENIED
// With dest or with diskStorage then you also need to add
// __dirname here
if (!fs.existsSync("./thoughts")) {
  fs.mkdir("./thoughts", (err) => {});
}

const storage = multer.diskStorage({
  // YOU NEED TO USE THE __dirname, IT WILL NOT WORK WITHOUT IT
  destination: (req, file, cb) => cb(null, __dirname + `/thoughts`),
  // Always give a UNIQUE filename so that the file is not overwritten
  filename: (req, file, cb) => cb(null, `${Date.now()}-${file.originalname}`),
});

const fileFilter = (req, file, cb) => {
  // This part is not needed but if you want to check
  if (file.mimetype.includes("image")) {
    cb(null, true);
  } else {
    // Returning false will reject it,
    // your req.file will be undefined
    cb(null, false);
  }
};

const upload = multer({
  storage,
  limits: {
    // 5MB is the max size allowed
    fileSize: 1024 * 1024 * 5,
  },
  fileFilter,
});

This is a working example where everything is fixed. Always check __dirname, make sure you give the correct file path 'upload' -> './upload' and simmilar. I think that for someone vs code may not able to create dirs and add files because they don't have permissions, make sure to double check that.

started
started time in 1 day ago