Logo

dev-resources.site

for different kinds of informations.

Problem Encountered with CORS in Deno Server

Published at
2/4/2024
Categories
deno
cors
webdev
oakcors
Author
mich0w0h
Categories
4 categories in total
deno
open
cors
open
webdev
open
oakcors
open
Author
8 person written this
mich0w0h
open
Problem Encountered with CORS in Deno Server

Problem Encountered with CORS in Deno Server

Recently, I encountered an issue while developing a server using Deno. My objective was to enable CORS (Cross-Origin Resource Sharing) requests utilizing the oakCors middleware. Despite setting it up as per the documentation, CORS handling did not function as expected.

The Scenario

I employed Deno's Oak framework to create the server and handle incoming requests from the frontend. Below is a snippet of the code used (some parts are modified for brevity and clarity):

import { Application, Router } from "https://deno.land/x/oak/mod.ts";
import { oakCors } from "https://deno.land/x/cors/mod.ts";

const router = new Router();
router.post("/", async (context) => {
    const body = await context.request.body();
    console.log(body.text());
});

const app = new Application();
app.use(router.routes());
app.use(router.allowedMethods());

// Enabling CORS for port 5173 on localhost using oakCors
app.use(
  oakCors({
    origin: "http://localhost:5173",
    optionsSuccessStatus: 200,
    methods: "POST, OPTIONS",
  }),
);

await app.listen({ port: 8000 });
Enter fullscreen mode Exit fullscreen mode

Despite configuring the server to accept CORS requests from http://localhost:5173, requests to the server were being rejected due to CORS errors.

Analysis

It appears that the 'oakCors' middleware is not working correctly, and the CORS headers are not being added, as indicated by the error message I received:

Access to fetch at 'http://localhost:8000/api/generate' from origin 'http://localhost:5173' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Enter fullscreen mode Exit fullscreen mode

Solution

After some trial and error, I discovered that moving the configuration of oakCors before defining the routes resolved the issue.

import { Application, Router } from "https://deno.land/x/oak/mod.ts";
import { oakCors } from "https://deno.land/x/cors/mod.ts";

const app = new Application();

// Enabling CORS for port 5173 on localhost using oakCors
// make sure to initialize oakCors before the routers
app.use(
  oakCors({
    origin: "http://localhost:5173",
    optionsSuccessStatus: 200,
    methods: "POST, OPTIONS",
  }),
);

const router = new Router();
router.post("/", async (context) => {
    const body = await context.request.body();
    console.log(body.text());
});


app.use(router.routes());
app.use(router.allowedMethods());

await app.listen({ port: 8000 });
Enter fullscreen mode Exit fullscreen mode

I learned that I should configure middleware before the routes' are defined.

Remaining Challenge

According to the chapter "Enable CORS for a Single Route" of the official docs, these codes would work but didn't.

const corsOptions: oakCors.Options = {
  origin: "http://localhost:5173",
  optionsSuccessStatus: 200,
};

router.post("/", oakCors(corsOptions), (context) => {
    const body = await context.request.body;
    console.log(body.text());
});

Enter fullscreen mode Exit fullscreen mode

Although this issue remains unresolved at present, it does not impede the functionality of the server as I have implemented a workaround that meets my current requirements.

cors Article's
30 articles in total
Favicon
Cookies auto clearing after browser refresh issue , CORS related express cookies issue
Favicon
What is CORS Error and how to fix it
Favicon
CORS in Spring Boot with Kotlin
Favicon
Understanding CORS: Why Your API Requests Are Failing 🚧
Favicon
How to Launch Google Chrome Without CORS Protection on macOS
Favicon
Cross-Origin Resource Sharing (CORS): A Comprehensive Guide
Favicon
CORS is Stupid
Favicon
roadauth-rails api jwt cors 2024
Favicon
What is the CORS ?
Favicon
Fixing CORS in your SPA
Favicon
Advanced CORS: Deep Dive into Cross-Origin Resource Sharing
Favicon
Third-Party Cookies Are Gone (Or Not). How Can I Still Embed Cross-Site Apps?
Favicon
SOLVING CORS ERROR
Favicon
Troubleshooting CORS Issues in Express.js: A Simple Misconfiguration
Favicon
Implementing CORS in a Custom Next.js Server
Favicon
What are CORS? and how to configure it in Node?
Favicon
Brewing a More Open Web: CORS Demystified
Favicon
CORS Error Explained and How to Fix It?
Favicon
Resolving CORS Issues in express Node.js Project
Favicon
Resolving Firebase Authentication Sign-in Method Error
Favicon
Problem Encountered with CORS in Deno Server
Favicon
Solving CORS errors with Appwrite
Favicon
Need Help: Cross-Origin-Opener-Policy Blocking Google Login Window.Closed Call
Favicon
Understanding CORS, CSRF attacks and enabling valid CORS
Favicon
Enabling CORS in a .NET Core Server-Side Application
Favicon
[SOLVED]Yet another docker + vite, The connection was reset
Favicon
Cross-Origin Resource Sharing (CORS)
Favicon
Modern API development(Part 2): Initialize Server
Favicon
Configurando CORS Global para API Springboot
Favicon
Understand CORS 🌐 in Easy Way🦾

Featured ones: