0

I have these two files below, I'll try and be specific as possible to get a good answer. I have used express but never Koa, although the same founders but anyways I'm having trouble with this simple technical assessment.

They want a React app form to post a search term to the backend which is running the Koa server below. Once I pass the search term to the backend, then they want me to use isomorphic-fetch to make a request to the Dogs API they have listed, and then pass that data back to the front-end. In the end, I need to be able to have the picture of the dog that was originally entered to be on the screen.

The confusion I guess is I can't seem to get the form on the front to correctly post to the backend, I've never used Koa, I know in express I could just req.params, I've tried reading the Koa documentation but I must be missing something because I cannot get this right and I only have one day left.

I will post my attempts and code as well as the original starter code they gave me if that helps see what I'm trying to do here. I'm not getting very far.

The next two blocks of code are mine, the bottom two starter code.

import React, { useState } from "react";
import "./App.css";
import axios from "axios";

  const handleSubmit = async () => {
    const response = await fetch(`http://localhost:3011/search/${searchTerm}`, {
      method: "POST",
      body: JSON.stringify({
        searchTerm: searchTerm,
      }),
      headers: {
        "Content-type": "application/json; charset=UTF-8",
      },
    });
    const data = await response.json();
    console.log(data);
  };

  const handleChange = (e) => {
    e.preventDefault();
    setSearchTerm(e.target.value);
    console.log(searchTerm);
  };

  return (
    <div className="App">
      <h1>Lots of dogs! </h1>
      <p>See photos of your favorite dogs</p>
      <form>
        <input
          type="text"
          onChange={handleChange}
          name="breed"
          placeholder="Enter a dog breed"
        ></input>
        <button type="submit" onSubmit={handleSubmit}>
          Fetch
        </button>
      </form>
    </div>
  );
}

export default App;

^^ Mine, I put in a React app.

import Koa from "koa";
import Router from "@koa/router";
import cors from "@koa/cors";
import fetch from "isomorphic-fetch";
import serve from "koa-static";

const app = new Koa();
const router = new Router();
const port = 3011;

app.use(cors({ origin: "*" }));

const format = (str) => str.toLowerCase().replace(/\s/g, "");

app.use(cors({ origin: "*" }));

router.get("/", (ctx) => {
  ctx.body = "hello!";
});

app.use(async (ctx, next) => {
  await next();
  const rt = ctx.response.get("X-Response-Time");
  console.log(`${ctx.method} ${ctx.url} - ${rt}`);
});

app.use(async (ctx, next) => {
  const start = Date.now();
  await next();
  const ms = Date.now() - start;
  ctx.set("X-Response-Time", `${ms}ms`);
});

router.get("/search/:breed", async (ctx, next) => {
  const { breed } = ctx.params;
  console.log(breed);
  const { message } = await fetchBreedImage(format(breed));
  ctx.body = message;
  console.log(message);
});

const fetchBreedImage = (breed) =>
  fetch(`https://dog.ceo/api/breed/${breed}/images`)
    .then((res) => res.json())
    .catch((err) => console.log({ err }));

app.use(serve("./static"));

app.use(router.routes());

app.listen(port, () => {
  console.log(`Server running on http://localhost:${port}`);
});

^^^ My attempt to get this working... Below is the starter code they gave me. Just getting that working would be such a blessing. Thank you.

import Koa from 'koa';
import Router from '@koa/router';
import cors from '@koa/cors';
import fetch from 'isomorphic-fetch';

const app = new Koa();
const router = new Router();
const port = 3011;

app.use(cors({origin: '*'}));

router.get('/', (ctx) => {
    ctx.body = 'hello!';
});

app.use(async (ctx, next) => {
    await next();
    const rt = ctx.response.get('X-Response-Time');
    console.log(`${ctx.method} ${ctx.url} - ${rt}`);
});

app.use(async (ctx, next) => {
    const start = Date.now();
    await next();
    const ms = Date.now() - start;
    ctx.set('X-Response-Time', `${ms}ms`);
});

app.use(router.routes());

app.listen(port, () => {
    console.log(`Server running on http://localhost:${port}`);
});




<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/water.css@2/out/water.css">
    <title>Lots of dogs! </title>
</head>
<body>
    <h1>Lots of dogs! </h1>
    <p>See photos of your favorite dogs</p>
    <form>
        <input type="text" name="breed" placeholder="Enter a dog breed">
        <button type="submit">Fetch</button>
    </form>
</body>
</html>
Brendan F
  • 19
  • 1

0 Answers0