markusahlstrand / cloudworker-router Goto Github PK
View Code? Open in Web Editor NEWA minimal router for cloudflare workers
License: MIT License
A minimal router for cloudflare workers
License: MIT License
Hey there, I followed the example code to set up a server. For reference, here is my code:
const Router = require("cloudworker-router");
const app = new Router();
console.log(Router);
app.get("/pet", async (ctx) => {
var votes = await ssfinal.get("votes");
var names = JSON.parse(await ssfinal.get("names"));
var name = ctx.params.name;
await ssfinal.put("votes", votes+1);
votes += 1;
names.push(name);
await ssfinal.put("names", JSON.stringify(names));
return new Response(votes);
});
app.get("/votes", async (ctx) => {
var votes = await ssfinal.get("votes");
return new Response(votes);
})
addEventListener("fetch", (event) => {
event.respondWith(app.resolve(event));
});
But when I run wrangler dev
, I get this error: ```
▲ [WARNING] Converting "require" to "esm" is currently not supported
index.js:1:15:
1 │ const Router = require('cloudworker-router');
Uncaught TypeError: Router is not a constructor
I assume this is an issue with not packing everything into one file with webpack. Any idea how I can do this?
Hello!
Just checked out this module and wanted to try it.
After setting it up, it seems like there is no data inside ctx.request
and ctx.query
etc. event though a form body was posted.
Same happens with simple GET requests.
Is this a known issue or just an user error?
This is my setup:
index.ts
import { Router } from 'cloudworker-router'
const router = new Router();
router.post('/hello/:name', async (ctx) => {
return new Response(JSON.stringify(ctx));
});
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
return router.handle(request, env, ctx);
},
};
And this is the result:
I'm trying to add authentication middleware to a route, the same way I use it on Express.
router.get('/e', async (ctx) => {
ctx.body = 'Hello World2';
ctx.status = 200;
});
router.get('/a', userAuthCheck, async (ctx) => {
ctx.body = 'Hello World2';
ctx.status = 200;
});
The userAuthCheck
has code that validates a user's credentials and gets their user ID and some other information which I use later in the code. When I include the middleware, I get 404 however without it everything is fine.
Even if I get 404, I can console log in the middleware and see it so clearly the code is being reached.
I was wondering whether I'm doing it wrong or if it's just not supported this way?
Thanks again!
Nice repo, thanks!
However I might have missed something down the road: what can we do besides set ctx.status
and ctx.body
??
I naively tried:
router.post('/hello', async (ctx) => {
try {
const body = await ctx.event.request.json()
ctx.body = JSON.stringify(body)+'\n';
ctx.status = 200;
} catch (error) {
ctx.status = 401;
}
});
status code is never set because of the await
function.
Is there a way to decide when to return
?
Something like:
router.post('/hello', async (ctx) => {
try {
const body = await ctx.event.request.json()
return res.status(200).json(body)
} catch (error) {
return res.status(401)
}
});
Hello,
Do you plan to add TypeScript support for this module ?
Thanks.
This package is listed on NPM as MIT licensed, but there is no license in the REPO which makes forking it (or even using it) risky. Can you consider adding an explicit license in your repo? ie: LICENSE.md file
Cloudflare adds country codes to each request. Maybe there's a way to add support for routing on any header?
Hi,
Is there a way to handle redirects/301/302?
Thanks,
Chris
With the new module worker syntax (https://developers.cloudflare.com/workers/runtime-apis/fetch-event/#syntax-module-worker) bindings
are no longer global. Instead they are passed as a second argument to exportefetch
function. With that being said, it would be useful to be able to pass those bindings
to the routes' context, either within state
object or within it's own special property env
/ bindings
.
A work around is you can pass a modified request
with the bindings
to the Router.handle
, but this causes a typing issue & then to use the bindings
you need to dig into ctx.event.request
. It would be preferable to be able to add the bindings
directly to routes' context.
I was just trying to use your router to migrate an API to cloudflare workers, while testing I noticed that the middleware system doesn't work right.
This will return 404 for no reason:
const Router = require('cloudworker-router')
const router = new Router()
router.get('/test', async (ctx, next) => {
next()
}, async ctx => {
ctx.status = 204
})
addEventListener('fetch', event => {
event.respondWith(router.resolve(event))
})
Maybe I'm just doing it wrong, but it's not really documented.
I'm not sure how to implement middleware. If an auth middleware passes, how do I continue onto the next handler?
Add a function for options requests and respond to OPTIONS requests with allowed methods.
Hello, how can I add "Access-Control-Allow-Origin" header in my requests?
I tried few things but nothing works till now, I assume that there is a easier method to do it?
My code looks like this:
import { Router } from "cloudworker-router";
import cors from "cors";
const router = new Router();
router.get("/search", async (context) => {
const symbol = new URL(context.request.url).searchParams.get("query");
return fetch(`https://query1.finance.yahoo.com/v11/finance/quoteSummary/${symbol}?modules=financialData`);
});
router.get("/getSymbolData", async (context) => {
const query = new URL(context.request.url).searchParams.get("symbol");
return fetch(`https://query1.finance.yahoo.com/v1/finance/search?q=${query}`);
});
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
return router.handle(request, env, ctx);
},
};
How to pass allow request from origin?
Hello,
I want to know how to send file to response/render an external html file like Express.js response.sendFile(__dirname + './home.html');
Can you help me?
First of all, thanks for creating this. I've been looking in using Cloudflare Workers more and this will really help make it easier.
When I install the module from NPM and make an index.js then run wrangler preview
, I see this. https://i.imgur.com/32OKd0I.png
const router = require('cloudworker-router');
router.get('/', async (ctx) => {
ctx.body = 'Hello World';
ctx.status = 200;
});
addEventListener('fetch', event => {
event.respondWith(router.resolve(event));
})
Is there any other code I need which I can find an example from? I'm terribly sorry if this is a dumb question.
Thanks!
Any ways to return a html content? Can I set the response header?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.