APIs and CORS
Learning objectives
- You know of the concept of Cross-Origin Resource Sharing (CORS).
- You know how to implement an API with Hono that allows CORS.
Services offered over the web server can be accessed practically from anywhere unless explicitly denied. By default, queries made using JavaScript from the browser are limited to the current domain. That is, for example, JavaScript code retrieved as a part of a page from aalto.fi
cannot be used to make queries to another domain, unless the server responding to requests in the other domain explicitly allows this.
Allowing requests outside the current domain is done using a Cross-Origin Resource Sharing (CORS) policy. In practice, when using CORS, the server adds information to response headers indicating whether cross-origin requests (i.e. requests from other domains) are allowed.
If we wish to allow cross-origin requests in our applications, the easiest approach is to use existing middleware. Hono comes with a cors middleware, which allows easy configuration of cross-origin requests. The following example outlines how to allow cross-origin requests to a Hono application.
import { Hono } from "https://deno.land/x/hono@v3.12.11/mod.ts";
import { cors } from "https://deno.land/x/hono@v3.12.11/middleware.ts";
const app = new Hono();
app.use('/*', cors())
const data = {
name: "Karen Spärck Jones",
yearOfBirth: 1935,
title: "Professor",
};
app.get("/", (c) => c.json(data));
Deno.serve(app.fetch);
Now, when we make a request to the server, we see a header access-control-allow-origin
that is used to policy cross-origin requests. In this case, requests from browsers accessing sites in any domain can be made to the server.
curl -v localhost:8000
..
< access-control-allow-origin: *
..
{"name":"Karen Spärck Jones","yearOfBirth":1935,"title":"Professor"}