布鲁诺 普雷托
布鲁诺 普雷托
Explore posts from servers
CDCloudflare Developers
Created by 布鲁诺 普雷托 on 11/8/2024 in #pages-help
Serving Static Files - Hono
So I am trying to convert a previous project of mine from express to Hono (IDK if its the best option or not.. I'd like some feedback/advice). I always start by deploying static stuff to check if everything is according to plan, however I don't seem to be able and serve my static 404 page. From what I gather I have to add to the toml file the following:
assets = { directory = "src/public", binding = "ASSETS", html_handling = "force-trailing-slash", not_found_handling = "404-page" }
assets = { directory = "src/public", binding = "ASSETS", html_handling = "force-trailing-slash", not_found_handling = "404-page" }
Am I suppose to add something else in my index.ts file ? I saw Hono has the following possibility
app.notFound((c) => {
return c.text('Oops not found.', 404)
})
app.notFound((c) => {
return c.text('Oops not found.', 404)
})
I can serve the file if I past it plain in the index.ts file, however for code/folder structure purposes I prefer not to do so... I'd really appreciate some help in this manner. Cheers :cheers:
1 replies
CDCloudflare Developers
Created by 布鲁诺 普雷托 on 7/20/2024 in #workers-help
R2 via workers returnind undefined for list, get, delete and put requests
I have everythin in 'modules' to organize the code better index.js pageHandler.js corsHandler.js I created a bucket so that the static and dynamic html files can be fetched When I call the pageHandler from index I send the request, env and ctx as parameters,however it seems to not pass the object at all
import {corsOptions} from "./corsHandler";

const handlePages=async (request, env, ctx, trigger='404') => {
switch (true) {
case "200": {
return new Response(JSON.stringify({res: "Hi"}), {status: 200})
}
default :
return await handle404Pages(request, env, ctx)
}
}


const returnPage=async (htmlResponse, request, status=200) => {
switch (request.method) {
case 'GET':
return new Response(htmlResponse, {
status: status,
headers: {
'Content-Type': 'text/html'
}
});
default:
const responseData={
"status": "Not Found"
}
const jsonResponse=JSON.stringify(responseData)
// Return JSON response with appropriate CORS headers
return new Response(jsonResponse, corsOptions(request), 404);

}
}

const getPageR2=async (env, page) => {
return await env.STORE.get(`src/html/${page}.html`)
}

async function handle404Pages(request, env, ctx) {

const ContactMeObject=JSON.stringify(env.CONTACTME);
console.log(ContactMeObject)
const object=await getPageR2(env, "404")
if (object === null) {
return new Response('Object Not Found', {status: 404});
}
console.log(JSON.stringify(object))
const htmlContent=object
.replace('{{URL}}', ContactMeObject['WHERE'])
.replace('{{CONTACT}}', ContactMeObject[ContactMeObject['WHERE']]);
return await returnPage(htmlContent, request, 404)
}


export {handlePages}
import {corsOptions} from "./corsHandler";

const handlePages=async (request, env, ctx, trigger='404') => {
switch (true) {
case "200": {
return new Response(JSON.stringify({res: "Hi"}), {status: 200})
}
default :
return await handle404Pages(request, env, ctx)
}
}


const returnPage=async (htmlResponse, request, status=200) => {
switch (request.method) {
case 'GET':
return new Response(htmlResponse, {
status: status,
headers: {
'Content-Type': 'text/html'
}
});
default:
const responseData={
"status": "Not Found"
}
const jsonResponse=JSON.stringify(responseData)
// Return JSON response with appropriate CORS headers
return new Response(jsonResponse, corsOptions(request), 404);

}
}

const getPageR2=async (env, page) => {
return await env.STORE.get(`src/html/${page}.html`)
}

async function handle404Pages(request, env, ctx) {

const ContactMeObject=JSON.stringify(env.CONTACTME);
console.log(ContactMeObject)
const object=await getPageR2(env, "404")
if (object === null) {
return new Response('Object Not Found', {status: 404});
}
console.log(JSON.stringify(object))
const htmlContent=object
.replace('{{URL}}', ContactMeObject['WHERE'])
.replace('{{CONTACT}}', ContactMeObject[ContactMeObject['WHERE']]);
return await returnPage(htmlContent, request, 404)
}


export {handlePages}
3 replies
CDCloudflare Developers
Created by 布鲁诺 普雷托 on 7/14/2024 in #workers-help
CORS Missing Allow Origin
I am havin problems with the Cors, the code I'm about to send here worked before, out of the blue it stopped working, is anyone able to help out?
if (request.method === 'OPTIONS') {
// Handle CORS preflight req
return new Response(JSON.stringify({cors:'allowed'}), corsOptions(request.headers.get('Origin')));
}

function corsOptions(origin, status = 0) {
return {
status: status ? 404:200,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': origin,
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Credentials': "true",
'Access-Control-Expose-Headers': 'Set-Cookie',
'Same-Site': 'Strict'
}
};
}
if (request.method === 'OPTIONS') {
// Handle CORS preflight req
return new Response(JSON.stringify({cors:'allowed'}), corsOptions(request.headers.get('Origin')));
}

function corsOptions(origin, status = 0) {
return {
status: status ? 404:200,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': origin,
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Credentials': "true",
'Access-Control-Expose-Headers': 'Set-Cookie',
'Same-Site': 'Strict'
}
};
}
1 replies
CDCloudflare Developers
Created by 布鲁诺 普雷托 on 7/10/2024 in #workers-help
Error: D1_ERROR: near "MERGE": syntax error at offset 3
MERGE INTO pt_player_tribe AS target
USING (SELECT ?1 AS player_id, ?2 AS tribe_id, ?3 AS world) AS source
ON (target.player_id = source.player_id AND target.world = source.world)
WHEN MATCHED AND target.tribe_id <> source.tribe_id THEN
UPDATE SET tribe_id = source.tribe_id
WHEN NOT MATCHED THEN
INSERT (player_id, world, tribe_id)
VALUES (source.player_id, source.world, source.tribe_id)
MERGE INTO pt_player_tribe AS target
USING (SELECT ?1 AS player_id, ?2 AS tribe_id, ?3 AS world) AS source
ON (target.player_id = source.player_id AND target.world = source.world)
WHEN MATCHED AND target.tribe_id <> source.tribe_id THEN
UPDATE SET tribe_id = source.tribe_id
WHEN NOT MATCHED THEN
INSERT (player_id, world, tribe_id)
VALUES (source.player_id, source.world, source.tribe_id)
2 replies
CDCloudflare Developers
Created by 布鲁诺 普雷托 on 7/10/2024 in #workers-help
✘ [ERROR] Error: The 'mode' field on 'RequestInitializerDict' is not implemented.
✘ [ERROR] Error: The 'mode' field on 'RequestInitializerDict' is not implemented.
4 replies
CDCloudflare Developers
Created by 布鲁诺 普雷托 on 4/11/2024 in #general-help
Cloudflare calls
Can someone help me out with this?
4 replies
CDCloudflare Developers
Created by 布鲁诺 普雷托 on 3/2/2024 in #workers-help
Serve js files or json responses
I wanna do something like this with cloudflare workers:
const express = require('express');
const fs = require('fs');
const path = require('path')
const bodyParser = require('body-parser');
const helmet = require('helmet');
const cors = require('cors'); // Add this line
const basicAuth = require('express-basic-auth');
const bcrypt = require('bcrypt');
const app = express();
const port = 3005;
const config = require('./config.json');
const mysql = require("mysql");


//Some DB connection, probably mongo


app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'"],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", "data:"],
connectSrc: ["'self'"],
fontSrc: ["'self'"],
objectSrc: ["'none'"],
mediaSrc: ["'self'"],
frameSrc: ["'none'"],
},
}, dnsPrefetchControl: false, frameguard: {
action: 'deny'
}, hsts: {
maxAge: 5184000, // 60 days
includeSubDomains: true, preload: true,
}, ieNoOpen: true, noSniff: true, permittedCrossDomainPolicies: {
permittedPolicies: 'none',
}, referrerPolicy: {
policy: 'same-origin',
}, xssFilter: true,
}));

const corsOptions = {
origin: /.*somedomain.*/, credentials: true, exposedHeaders: 'Set-Cookie',
sameSite: 'Strict',
};

// Apply CORS middleware before body parsing
app.use(cors(corsOptions));


// Body parser with increased limits
app.use(bodyParser.json({limit: '1gb'}));
app.use(bodyParser.urlencoded({limit: '1gb', extended: true}));

app.use(express.static(path.join(__dirname, 'public')));
const excludedRoutes = [''];

// Basic authentication middleware
app.use((req, res, next) => {
// Check if the request path matches any of the excluded routes
if (excludedRoutes.includes(req.path)) {
// If the request path matches, skip basic authentication and move to the next middleware
next();
} else {
// If the request path doesn't match, proceed with basic authentication
basicAuth({
users,
challenge: true,
unauthorizedResponse: 'Unauthorized access',
})(req, res, next); // Call the basicAuth middleware
}
});


//part I actually want to implement
app.get('/get-data', (req,res)=>{
res.json('{"somedata":"some other data"}')
})
const express = require('express');
const fs = require('fs');
const path = require('path')
const bodyParser = require('body-parser');
const helmet = require('helmet');
const cors = require('cors'); // Add this line
const basicAuth = require('express-basic-auth');
const bcrypt = require('bcrypt');
const app = express();
const port = 3005;
const config = require('./config.json');
const mysql = require("mysql");


//Some DB connection, probably mongo


app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'"],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", "data:"],
connectSrc: ["'self'"],
fontSrc: ["'self'"],
objectSrc: ["'none'"],
mediaSrc: ["'self'"],
frameSrc: ["'none'"],
},
}, dnsPrefetchControl: false, frameguard: {
action: 'deny'
}, hsts: {
maxAge: 5184000, // 60 days
includeSubDomains: true, preload: true,
}, ieNoOpen: true, noSniff: true, permittedCrossDomainPolicies: {
permittedPolicies: 'none',
}, referrerPolicy: {
policy: 'same-origin',
}, xssFilter: true,
}));

const corsOptions = {
origin: /.*somedomain.*/, credentials: true, exposedHeaders: 'Set-Cookie',
sameSite: 'Strict',
};

// Apply CORS middleware before body parsing
app.use(cors(corsOptions));


// Body parser with increased limits
app.use(bodyParser.json({limit: '1gb'}));
app.use(bodyParser.urlencoded({limit: '1gb', extended: true}));

app.use(express.static(path.join(__dirname, 'public')));
const excludedRoutes = [''];

// Basic authentication middleware
app.use((req, res, next) => {
// Check if the request path matches any of the excluded routes
if (excludedRoutes.includes(req.path)) {
// If the request path matches, skip basic authentication and move to the next middleware
next();
} else {
// If the request path doesn't match, proceed with basic authentication
basicAuth({
users,
challenge: true,
unauthorizedResponse: 'Unauthorized access',
})(req, res, next); // Call the basicAuth middleware
}
});


//part I actually want to implement
app.get('/get-data', (req,res)=>{
res.json('{"somedata":"some other data"}')
})
How to do this, if possible
5 replies