🌐http-endpoints
- プラグイン
- valtown
- ソース
- GitHub で見る ↗
説明
次のような場合に使用: HTTP val を構築する場合 — Web エンドポイント、API ルート、Webhook レシーバー、または HTTP リクエストに応答する任意の val。 ハンドラーのシグネチャ、Hono の使い方、エンドポイント URL、CORS の挙動、リダイレクト、および Val Town 固有の制限事項について説明します。
原文を表示
Use when building an HTTP val — a web endpoint, API route, webhook receiver, or any val that responds to HTTP requests. Covers the handler signature, Hono usage, the endpoint URL, CORS behavior, redirects, and Val Town-specific limitations.
ユースケース
- ✓Web エンドポイントを構築するとき
- ✓API ルートを作成するとき
- ✓Webhook レシーバーを設定するとき
- ✓HTTP リクエストに応答するとき
本文(日本語訳)
HTTP エンドポイント
HTTP val(fileType: "http")はリクエストハンドラをエクスポートし、受信する HTTP リクエストのたびに実行されます。
各 HTTP ファイルにはパブリックなライブ URL が割り当てられます —— URL を自分で構築しないでください。
list_files または create_file のレスポンスに含まれる links.endpoint を参照するか、fetch_val_endpoint を呼び出してください。
基本的なハンドラ
// 詳細: https://docs.val.town/vals/http/
export default async function (req: Request): Promise<Response> {
return Response.json({ ok: true });
}
ファイルには export が必要です —— ハンドラには export default を使用します。
Hono
Hono を使用する場合は、app ではなく app.fetch をエクスポートしてください:
import { Hono } from "npm:hono";
import { parseVal, serveFile } from "https://esm.town/v/std/utils/index.ts";
const app = new Hono();
app.get("/", (c) => c.text("hello"));
// フロントエンドのファイルをすべてトランスパイルし、正しい Content-Type で配信
app.get("/frontend/**/*", (c) => serveFile(c.req.path));
// ソース表示へのリダイレクト
app.get("/source", (c) => c.redirect(parseVal().links.self.val));
// エラー発生時にフルスタックトレースを表示するため、常にこれを追加:
app.onError((err) => Promise.reject(err));
export default app.fetch;
Hono の serveStatic は Val Town では動作しません。
静的ファイルの配信には std/utils の serveFile / staticHTTPServer を使用してください。
std/utils の完全な API(readFile、serveFile、staticHTTPServer、listFiles、listFilesByPath、httpEndpoint、parseVal など)については、https://utilities.val.run/docs.md を参照してください。
CORS
Val Town はデフォルトで寛容な CORS ヘッダー(Access-Control-Allow-Origin: *)を付与するため、
99% のケースでは CORS について何も対応する必要はありません。
Hono の cors ミドルウェアを使用する必要はほぼありません。
CORS ヘッダーを1つでも自分で設定した場合、Val Town はデフォルトの CORS ヘッダーをすべて付与しなくなります。 CORS は完全に自前で処理するか、一切触れないかのどちらかにしてください。
リダイレクト
Val Town では Response.redirect は正常に動作しません。代わりに以下を使用してください:
return new Response(null, { status: 302, headers: { Location: "/path" } });
// または Hono の場合:
return c.redirect("/path");
利用できない機能
- WebSocket: Val Town は WebSocket の受信接続を受け付けません。 代わりにポーリング、ロングポーリング、またはサーバー送信イベント(SSE)を使用してください。
- ファイルシステムへのアクセス: プラットフォームの制約をご確認ください。
永続的な状態の保存には
std/sqliteまたはstd/blobを使用してください。
クライアントサイドのエラーを収集する
HTML レスポンスの場合、以下のスクリプトタグを追加することで、
ブラウザのエラーを val のログ(get_logs で確認可能)に送信できます:
<script src="https://esm.town/v/std/catch"></script>
変更の確認
HTTP val を編集したら、実際にフェッチして期待通りの HTTP レスポンスが返ることを確認してください。 この手順を踏まずに変更完了を報告しないでください。
原文(English)を表示
HTTP Endpoints
HTTP vals (fileType: "http") export a request handler and run on every incoming HTTP request. Each HTTP file is assigned a public live URL — never construct it yourself; read links.endpoint from list_files or create_file responses, or call fetch_val_endpoint.
Basic handler
// Learn more: https://docs.val.town/vals/http/
export default async function (req: Request): Promise<Response> {
return Response.json({ ok: true });
}
The file must have an export — export default for the handler.
Hono
When using Hono, export app.fetch (not app):
import { Hono } from "npm:hono";
import { parseVal, serveFile } from "https://esm.town/v/std/utils/index.ts";
const app = new Hono();
app.get("/", (c) => c.text("hello"));
// Serve all frontend files, transpiled, with correct content types
app.get("/frontend/**/*", (c) => serveFile(c.req.path));
// View source redirect
app.get("/source", (c) => c.redirect(parseVal().links.self.val));
// Always add this for full stack traces on errors:
app.onError((err) => Promise.reject(err));
export default app.fetch;
Hono's serveStatic does not work on Val Town. Use serveFile / staticHTTPServer from std/utils for static files. For the full std/utils API (readFile, serveFile, staticHTTPServer, listFiles, listFilesByPath, httpEndpoint, parseVal, …), fetch https://utilities.val.run/docs.md.
CORS
Val Town adds permissive CORS headers by default (Access-Control-Allow-Origin: *), so in 99% of cases, you should never need to do anything with CORS. Using Hono's cors middleware is almost always unnecessary.
If you set any CORS header yourself, Val Town stops adding all default headers — so either handle CORS completely yourself or don't touch it at all.
Redirects
Response.redirect is broken on Val Town. Use one of:
return new Response(null, { status: 302, headers: { Location: "/path" } });
// or, with Hono:
return c.redirect("/path");
What's not available
- WebSockets: Val Town does not accept incoming WebSocket connections. Use polling, long polling, or server-sent events instead.
- Filesystem access: see the platform constraints. For persistent state, use
std/sqliteorstd/blob.
Surfacing client-side errors
For HTML responses, add this script tag to send browser errors back to val logs (visible via get_logs):
<script src="https://esm.town/v/std/catch"></script>
Verifying changes
After editing an HTTP val, fetch it to confirm it returns the expected HTTP response. Do not report a change as done without this step.
原文・著作権は Anthropic および各プラグイン作者に帰属します。日本語訳は Claude API による自動翻訳です。