fetch-apikoactx

How to end a koa response


I have recently been making an application using VS code's live server and Koa.js for backend. My frontend script looks like the following

const submitButton = document.getElementById('button');

submitButton.addEventListener('click', async () => {
    await fetch('http://localhost:3000/getMessage).then(res => res.json()).then(data => alert(data.message));
    alert('breakpoint 2');
}

My backend (imports omitted) looks like the following

module.exports = (ctx) => {
    console.log('breakpoint 1');
    ctx.body = { message: "hello world" };
}

When I click on the button, the backend seems to work properly ('breakpoint 1' is printed in the backend console). however, no result is being printed or alerted on the browser or frontend console. It seems that the fetch call is never completed which is why. How can I end the call to the Koa server after setting ctx.body? thanks.


Solution

  • Backend seems to be fine but the frontend should be without an await (if you are using "then"):

    submitButton.addEventListener('click', () => {
        fetch('http://localhost:3000/getMessage).then(res => {
            res.json()).then(data => {
                alert('breakpoint 2');
                alert(data.message);
            })
        })
    }