1

when i send any data from req.body is defined but when trying to send multipart data(form) containing image from my browser req.body is undefined although i send the same request from postman and req.body is defiend my frontend code


    this.setState({
      editLoading: true
    });

    try{
      const form = new FormData()
      form.append('title', postData.title)
      form.append('content', postData.content)
      form.append('imageUrl', postData.image)
      const res = await axios({
        url: 'http://localhost:8080/feed/post',
        method: 'POST',
        data: form
      })

      if (res.status !== 200 && res.status !== 201) {
        throw new Error('Creating or editing a post failed!');
      }

      const post = {
        _id: res.data.post._id,
        title: res.data.post.title,
        content: res.data.post.content,
        creator: res.data.post.creator,
        createdAt: res.data.post.createdAt
      };
      this.setState(prevState => {
        let updatedPosts = [...prevState.posts];
        if (prevState.editPost) {
          const postIndex = prevState.posts.findIndex(
            p => p._id === prevState.editPost._id
          );
          updatedPosts[postIndex] = post;
        } else if (prevState.posts.length < 2) {
          updatedPosts = prevState.posts.concat(post);
        }
        return {
          posts: updatedPosts,
          isEditing: false,
          editPost: null,
          editLoading: false
        };
      });
    } catch (err) {
      console.log(err);
      this.setState({
        isEditing: false,
        editPost: null,
        editLoading: false,
        error: err
      });
    }

express config


const app = express()


app.use(express.json())
app.use(cors())
app.use(express.static(path.join(__dirname, 'images')))

this a screenshot of my request

PS the front end is using websocket

mohamed
  • 183
  • 1
  • 1
  • 8
  • I wonder if the data is being sent as `application/x-www-form-urlencoded` instead of json which would mean you need this middleware `app.use(express.urlencoded());` in order to parse the body into `req.body`. – jfriend00 Jan 12 '20 at 07:29
  • 1
    I would recommend you to use multer package at your backend to parse the file. https://www.npmjs.com/package/multer. After multer's parsing the file will be available at req.file. – Naor Levi Jan 12 '20 at 07:36
  • i thought like you but still undefined – mohamed Jan 12 '20 at 07:37
  • 1
    Have you looked at this post: https://stackoverflow.com/questions/37630419/how-to-handle-formdata-from-express-4 Specifically, the part about using a library like multer for processing multipart form data? – jfarleyx Jan 12 '20 at 07:39
  • 1
    The data is content-type `multipart/form-data` so you need middleware that will parse that or you need to tell axios to send the data as JSON or `application/x-www-form-urlencoded` instead and use the appropriate middleware for that. That's why `req.body` is empty - there's no middleware to parse the content-type the data is being sent in. FYI, `multer` can parse this type of data. – jfriend00 Jan 12 '20 at 07:56
  • it works when i used multer in my app.js file not in my router and i dont know why – mohamed Jan 12 '20 at 07:57
  • @mohamed - See my previous comment for why it works with multer. – jfriend00 Jan 12 '20 at 07:58

0 Answers0