javascriptnode.jsfile-uploadconfigurationblogs

POST http://localhost:3000/uploads 404 (Not Found)


I am trying to follow a tutorial video to create a blog.

On the step to upload a image i am getting a error.

I believe the error is because some mistake that I did in the server configuration, but I am not able to realize it because I am learning it.

So I would like some help with it..

Error on the browser

server.js

const express = require('express');
const path = require('path');
const fileupload = require('express-fileupload');

const app = express();

app.use(fileupload());

app.use(express.static(__dirname + 'public'));
app.use(express.static(__dirname + 'editor'));
app.use('/css',express.static(__dirname +'/css'));
app.use('/img',express.static(__dirname +'/img'));
app.use('/js',express.static(__dirname +'/js'));

app.get('/', (req, res) => {
    res.sendfile('./home.html');
})

app.get('/editor', (req, res) => {
    res.sendfile('./editor.html');
})

app.post('/uploads', (req, res) => {
    
    let file = req.files.image;
    let date = new Date();
    // image name
    let imagename = date.getDate() + date.getTime() + file.name;
    // image upload path
    let path = 'public/uploads/' + imagename;

    // create upload
    file.mv(path, (err, result) => {
        if(err){
            throw err;
        } else{
            // our image upload path
            res.json(`uploads/${imagename}`)
        }
    })
})



app.listen("3000", () => {
    console.log('listening......');
})e here

editor.js

const blogTitleField = document.querySelector('.title');
const articleField = document.querySelector('.article');

//banner
const bannerImage = document.querySelector('#banner-upload');
const banner = document.querySelector(".banner")
let bannerPath;

const publishBtn = document.querySelector('.publish-btn');
const uploadInput = document.querySelector("#image-upload");

bannerImage.addEventListener('change', () => {
    uploadImage(bannerImage, "banner");
})

uploadInput.addEventListener('change', () => {
    uploadImage(uploadInput, "image");
})

const uploadImage = (uploadFile, uploadType) => {
    const [file] = uploadFile.files;
    if(file && file.type.includes("image")){
        const formdata = new FormData();
        formdata.append('image', file);

        fetch('/uploads', {
            method: 'post',
            body: formdata
        }).then(res => res.json())
        .then(data => {
            if(uploadType == "image"){
                addImage(data, file.name);
            } else{
                bannerPath = `${location.origin}/${data}`;
                banner.style.backgroundImage = `url("${bannerPath}")`;
            }
        })
    } else{
        alert("upload Image only");
    }
}

const addImage = (imagepath, alt) => {
    let curPos = articleField.selectionStart;
    let textToInsert = '\r![$alt]($imagepath)\r';
    articleField.value = articleField.value.slice(0,curPos) + textToInsert + articleField.value.slice(curPos);

}

let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

publishBtn.addEventListener('click', () => {
    if ( articleField.value.length && blogTitleField.value.length ) {

        //generating id
        let letters = 'abcdefghijklmnopqrstuvwxyz';
        let blogTitle = blogTitleField.value.split(" ").join("-");
        let id = '';
        for(let i = 0; i < 4; i++){
            id += letters[Math.floor(Math.random() * letters.length)];
        }

        let docName = `${blogTitle}-${id}`;
        let date = new Date(); // for published at info

        //const budgets = this.budgetProvider.createBudgets(data.budgetList, projectId);//budgets
        // const budgets = arrayOfBudget.map((obj)=> {return Object.assign({}, obj)});


        //access firstore with db variable;
        db.collection("blogs").doc(docName).set({
            title: blogTitleField.value,
            article: articleField.value,
            bannerImage: bannerPath,
            publishedAt: `${date.getDate()} ${months[date.getMonth()]} ${date.getFullYear()}`
        })
        .then(() => {
            location.href = `/${docName}`;
        })
        .catch((err) => {
            console.error(err);
        })
    }
})

Edit

I did the change but the problem still in the same lines

I tried to edit the the files again to see if i did any typo, the the problem still.

The same error

I tried to get a better understand based on these examples.

POST http://localhost:3000/ 404 (Not Found) https://www.twilio.com/en-us/blog/handle-file-uploads-node-express


Solution

  • You are making a POST request, but there is no router available to accommodate it. Change the router specified as GET to post.

    app.post('/uploads', (req, res) => {
      // your codes goes here
    })