1. get请求
1.1 客户端
const res = await useFetch ( "/api/home?param1=abcd" , {
method : "GET" ,
headers : { "Content-Type" : "application/json" } ,
} ) ;
console. log ( "客户端接收get返回值" , res. data. value) ;
1.2 服务端 server/api/home/index.get.ts
export default defineEventHandler ( async ( event ) => {
const query = getQuery ( event) ;
console. log ( "服务端的query参数为:" , query. param1) ;
return { message : "Hello, World!" } ;
} ) ;
2. post请求
2.1 客户端
const res2 = await useFetch ( "/api/home" , {
method : "POST" ,
headers : { "Content-Type" : "application/json" } ,
body : JSON . stringify ( { comment : "test" } ) ,
} ) ;
console. log ( "客户端接收post返回值" , res2. data. value) ;
2.2 服务端 server/api/home/index.post.ts
export default defineEventHandler ( async ( event ) => {
const body = await readBody ( event) ;
console. log ( "服务的请求体:" , body) ;
return "Hello from server!" ;
} ) ;
3. 路径参数
3.1 客户端
const res3 = await useFetch ( "/api/home/abcd" , {
method : "GET" ,
headers : { "Content-Type" : "application/json" } ,
} ) ;
console. log ( "客户端接收路径参数返回值" , res3. data. value) ;
3.2 服务端 server/api/home/[id].get.ts
export default defineEventHandler ( async ( event ) => {
const id : string | undefined = event. context. params?. id;
console. log ( "路径参数" , id) ;
return { message : "Hello, " + id + "!" } ;
} ) ;