javascriptkoactx

How to fetch the result after sending a get request to Koa application


I am writing a program that sends a get request to a Koa backend, and retrieves the result using Fetch. The backend looks like

const koa = require('koa');
const router = require('koa-router');
const cors = require('koa2-cors');
const app = new koa();
app.use(cors());
const _ = router();
const port = 3000;

_.get('/', async (ctx) => {
    const result = "good morning";
    console.log(result);
    ctx.body = result;
});

app.use(_.routes());

app.listen(port, () => {
    console.log(`Server listening on port`);
});

The frontend looks like

submitButton.addEventListener('click', async () => {
    fetch(`http://localhost:3000/`)
        .then(res => console.log(res));
});

I am sure that the backend is functional, as when I press the submit button, the backend console is able to print the result correctly. But my frontend console is not printing anything. I have tried using alert(res) too. What might be going wrong here? Thanks.


Solution

  • first you need to parse response so

    submitButton.addEventListener('click', async () => {
    fetch(`http://localhost:3000/`)
        .then(res => res.json()) 
        .then(data => console.log(data)) 
        .catch(error => console.log(error));
    });