Dùng vnstock-js trong client component qua proxy có sẵn.
VietCap chặn request từ trình duyệt (CORS) và còn từ chối Origin lạ ở phía server. Thư viện kèm sẵn một proxy nhỏ để đặt trên server của bạn; client trên trình duyệt gọi qua đó.
// app/api/vnstock/[...path]/route.ts
import { nextHandler } from "vnstock-js/proxy";
export const { GET, POST } = nextHandler();
// components/price.tsx
"use client";
import { useEffect, useState } from "react";
import { createClient, type Quote } from "vnstock-js";
const vn = createClient({ proxy: "/api/vnstock" });
export function Price({ symbol }: { symbol: string }) {
const [q, setQ] = useState<Quote | null>(null);
useEffect(() => {
vn.stock(symbol).price().then(setQ);
}, [symbol]);
return <span>{q ? q.price.toLocaleString() : "…"}</span>;
}
import { workerHandler } from "vnstock-js/proxy";
export default { fetch: workerHandler() };
import express from "express";
import { expressHandler } from "vnstock-js/proxy";
const app = express();
app.use(expressHandler());
Cả ba hàm nhận cùng tuỳ chọn:
| Tuỳ chọn | Mặc định | Ý nghĩa |
|---|---|---|
basePath | /api/vnstock | Đường dẫn gắn proxy; client đặt proxy trùng giá trị này |
cacheSeconds | 30 | Số giây CDN được cache phản hồi GET thành công; 0 để tắt |
%2e%2e) bị chặn với 403.vn.vnstock-js/indicators: hàm thuần, không gọi mạng.watch() ở chế độ stream kết nối WebSocket tới SSI. Nếu WebSocket bị chặn trên môi trường của bạn, dùng { mode: 'poll' }.