Nuxt3服务端渲染(SSR)方式,请求需要放到server/api目录,整理两个请求简单封装。
Post请求
// server/api/all.post.ts
import winston from 'winston'
// 创建一个日志记录器
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'combined.log' })
]
})
export default defineEventHandler(async (event) => {
const config = useRuntimeConfig()
const reqBody = await readBody(event)
// 发送请求
const res = await $fetch(config.public.apiBase + reqBody.api, {
method: 'POST',
headers: { ...reqBody.headers, 'Content-Type': 'application/json' },
body: JSON.stringify(reqBody.params)
})
// 记录请求和响应的日志
logger.info(`Request: ${JSON.stringify(reqBody)}, Response: ${JSON.stringify(res)}`)
return res
})
Get请求
// server/api/all.get.ts
import winston from 'winston'
// 创建一个日志记录器
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'combined.log' })
]
})
export default defineEventHandler(async (event) => {
const config = useRuntimeConfig()
const query = getQuery(event)
// 发送请求
const res = await $fetch(config.public.apiBase + query.api, {})
return res
// 记录请求和响应的日志
logger.info(`Request: ${JSON.stringify(query)}, Response: ${JSON.stringify(res)}`)
return res
})
请求例子
一个post请求:
const { data: bannerApi } = await useFetch('/api/all', {
method: 'POST',
body: {
params: {
adId: '',
adType: '1',
pageNum: 1,
pageSize: 9999
},
api: '/api/cms/content/qry_pic_ad_page'
}
})
一个get请求:
const { data: randomCode } = await useFetch('/api/all', {
method: 'GET',
params: {
api: '/api/client/auth/randomCode'
}
})
文章版权归 有个狸 所有,未经许可不得转载,责任编辑:有个狸。