SvelteKit 允许你创建的不仅仅是页面。我们还可以通过添加导出与 HTTP 方法对应的函数的 +server.js
文件来创建 API 路由:GET
、PUT
、POST
、PATCH
和 DELETE
。
¥SvelteKit allows you to create more than just pages. We can also create API routes by adding a +server.js
file that exports functions corresponding to HTTP methods: GET
, PUT
, POST
, PATCH
and DELETE
.
当你单击按钮时,此应用从 /roll
API 路由获取数据。通过添加 src/routes/roll/+server.js
文件创建该路由:
¥This app fetches data from a /roll
API route when you click the button. Create that route by adding a src/routes/roll/+server.js
file:
export function GET() {
const number = Math.floor(Math.random() * 6) + 1;
return new Response(number, {
headers: {
'Content-Type': 'application/json'
}
});
}
单击按钮现在可以正常工作。
¥Clicking the button now works.
请求处理程序必须返回 响应 对象。由于从 API 路由返回 JSON 很常见,因此 SvelteKit 提供了一个方便的函数来生成这些响应:
¥Request handlers must return a Response object. Since it’s common to return JSON from an API route, SvelteKit provides a convenience function for generating these responses:
import { json } from '@sveltejs/kit';
export function GET() {
const number = Math.floor(Math.random() * 6) + 1;
return new Response(number, {
headers: {
'Content-Type': 'application/json'
}
});
return json(number);
}
<script>
/** @type {number} */
let number = $state();
async function roll() {
const response = await fetch('/roll');
number = await response.json();
}
</script>
<button onclick={roll}>Roll the dice</button>
{#if number !== undefined}
<p>You rolled a {number}</p>
{/if}