Click here to Skip to main content
15,507,526 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am using MERN stack, I don't why the page reloads after successful submission of the file via Axios to the server.

BACKEND

const express = require('express')
const router = express.Router()
const { check, validationResult } = require('express-validator/check')
const auth = require('../middleware/auth')
const User = require('../models/User')
const Blogs = require('../models/Blogs')
const multer = require('multer');
const Profile = require('../models/Profile')
let path = require('path');

console.log(__filename)

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, '../client/public/uploads/');
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname);
    }
});

const fileFilter = (req, file, cb) => {
    const allowedFileTypes = ['image/jpeg', 'image/jpg', 'image/png'];
    if (allowedFileTypes.includes(file.mimetype)) {
        cb(null, true);
    } else {
        cb(null, false);
    }
}

let upload = multer({ storage, fileFilter });

router.post('/', [auth, upload.single('postImage'), [
    check('text', 'Text is Required').not().isEmpty()
]], async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        return res.status(400).json({ errors: errors.array() })
    }

    try {
        const user = await User.findById(req.user.id).select('-password');

        const photo = req.file.filename;

        const newPost = new Blogs({
            title: req.body.title,
            text: req.body.text,
            name: user.name,
            avatar: user.avatar,
            user: req.user.id,
            postImage: photo
        })

        const post = await newPost.save()
        res.json(post)

    } catch (err) {
        console.log(err.message)
        res.status(500).send('Server Error')
    }
})


What I have tried:

FRONTEND

<pre lang="Javascript">
<pre>import React, { useState } from 'react'
import styled from 'styled-components';
import { useHistory } from 'react-router-dom'
import axios from 'axios';

const AddPost = () => {

    const [post, setPost] = useState()
    const [title, setTitle] = useState()
    const [fileName, setFileName] = useState()
    const history = useHistory()

    const handleFile = (e) => {
        setFileName(e.target.files[0])
    }

    const handleSubmit = async (e) => {
        e.preventDefault()
        
        const formData = new FormData();
        formData.append('postImage', fileName);
        formData.append('text', post);
        formData.append('title', title);

        const headers = {
            'Content-Type': 'application/json',
            'x-auth-token': localStorage.getItem('TOKEN'),
        }

        axios.post('http://localhost:5000/api/blogs', formData, {
            headers: headers
        })
            .then(res => {
                console.log(res);
            })
            .catch(err => {
                console.log(err);
            });
    }

    return (
        <Home>
            <Container>
                <Left>
                    <SideNav>
                        <li>👻 Create A Post</li>
                    </SideNav>
                </Left>
                <Middle>
                    <FilterOption>
                        <h1>Edit</h1>
                        <h1>Preview</h1>
                    </FilterOption>
                    <Form onSubmit={handleSubmit} encType='multipart/form-data'>
                        <input
                            type="file"
                            accept=".png, .jpg, .jpeg"
                            name="postImage"
                            onChange={handleFile}
                        />
                        <input placeholder="Add your title here..." onChange={(e) => setTitle(e.target.value)} />
                        <textarea placeholder="Write your Amazing Words..." onChange={(e) => setPost(e.target.value)}></textarea>
                        <FilterOption2>
                            <button type='button' onClick={handleSubmit} className="create">Publish</button>
                        </FilterOption2>
                    </Form>
                </Middle>
            </Container>
        </Home>
    )
}
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900