Search code examples
javascriptnode.jsjsonfetchclient-server

Can anyone explain why my program is not showing the correct alert?


I have written this function which allows users to add images to the server. However, my alerts don't seem to be working. I've tried to console.log the alert messages instead of having them as alerts but that doesn't seem to work either. Any tips would be great. client.js

async function picsub(event){
    event.preventDefault();
    var image=document.getElementById('imageFile');
    const formData = new FormData();;
    formData.append('image',image.files[0]);
    let i={
        method:'POST',
        body:formData,

    }
    fetch('http://127.0.0.1:8090/pics', i).then((response) => {
        return response.text();
    }).then((response) => {
        if (response === 'success') {
            alert('pic added');
        } else {
            alert('An error has occurred');
        }
    }).catch((e) => {
        alert('An error has occurred');
    
    form.reset();

}

const form = document.getElementById("form");
form.addEventListener("submit", picsub);

server.js

const app = express();
const port = 8090;

let pictures=[];

app.post('/pics', (req, res) => {
    const pic = req.body;
    console.log(pic);
    pictures.push(pic);
    res.status(201);
});


Solution

  • In your express, you only setup the status, but you didn't send any message from server. So, your then or catch in fetch will be executed.

    then will be executed when you receive the response from server.
    catch will be executed when you have failed connection between client and server.

    In your case, you didn't send any response from server, fetch function will wait for response until timeout. But, you didn't setup any timeout. That means there are no response from server or any failed connection. So, your then or catch in fetch will not be executed. Unless, you shut down the server. But, browser will help you setup the default timeout, such as Chrome. It use 300 seconds as timeout.

    So, you need to send message with res.end("success") like below.

    app.get('/pics', function (req, res) {
        const pic = req.body;
        console.log(pic);
        pictures.push(pic);
        res.status(201).end("success");
    })
    

    And in your client.js, you should complete the bracket in the fetch function.

    fetch('http://127.0.0.1:8090/pics', i).then((response) => {
        return response.text();
    }).then((response) => {
        if (response === 'success') {
            alert('pic added');
        } else {
            alert('An error has occurred');
        }
    }).catch((e) => {
        alert('An error has occurred');
    }) // ===> here