当前位置:网站首页>[nuxt 3] (IX) server routing
[nuxt 3] (IX) server routing
2022-07-23 22:47:00 【choukin】
Whether it's a house 、 Stars or deserts , Are beautiful because of invisible things ! ———— 《 The little prince 》
Server routing
Nuxt Automatic scanning ~/server/api,~/server/routes, ~/server/middleware A file in a directory , To register Support API and Hot update of server handler .
Every file needs to pass defineEventHandler() Export a default function
The application can directly return JSON data , One Promise Or use event.res.end() To send a response
Example
Create a server/api/hello.ts file :
export default defineEventHandler((event) => {
return {
api: 'works'
}
})
Limit what you can use await $fetch('/api/hello') To call this routinely API
Server routing
~/server/api The file in will automatically add a route prefix to the route /api If you don't want to add /api Prefix , You can put them in ~/server/routes In the folder .
Example :
export default defineEventHandler(() => 'Hello World!')
The above example , Can be routed /hello visit ,http://localhost:300/hello
Server side middleware
Nuxt Will automatically read ~/server/middleware The files in generate middleware for your project .
The middleware program will check the request before requesting other server routes , Expand , Header information , Record request , Extend the request object .
The middleware handler should not return any data ( Do not close or respond to requests ), Just check or extend the request context , Or throw an exception .
Example :
export default defineEventHandler((event) => {
console.log('New request: ' + event.req.url)
})
export default defineEventHandler((event) => {
event.context.auth = { user: 123 }
})
Server assisted methods
Server routing is performed by unjs/h3 Empower , It provides a set of auxiliary methods .
::ReadMore{link="https://www.jsdocs.io/package/h3#package-index-functions" title="Available H3 Request Helpers"} ::
You can ~/server/utils Add more auxiliary methods in .
Examples of use
Match route parameters
Server routing can use dynamic parameters such as /api/hello/[name].ts, And then through event.context.params To get .
Example:
export default defineEventHandler(event => `Hello, ${event.context.params.name}!`)
You can use await $feetch(‘/api/hello/nuxt’) request API , Then get Hello,nuxt!
matching HTPP Method
The request file name can be suffixed .get.post.put.delete To match the request HTTP Method.
export default defineEventHandler(() => 'Test get handler')
export default defineEventHandler(() => 'Test post handler')
The above example , Match to /test:
GET method: return Test get handlerPOST method: return Test post handlerother method: return 404 error
Capture all routes
Capturing all routes helps to fallback route processing , for example , Create a name that is ~/server/api/foo/[...].ts The file of , Will register a capture all routes , Used to match routes that do not match , such as /api/foo/bar/baz
Example :
export default defineEventHandler(() => `Default foo handler`)
export default defineEventHandler(() => `Default api handler`)
Use body To process requests
export default defineEventHandler(async (event) => {
const body = await useBody(event)
return { body }
})
Now you can use fetch('/api/submit', { method: 'post', body: { test: 123 } }) Way to call this API.
We are in the file name submit.post.ts Match post Method to get the request body , If in a get Use... In request useBody, Will throw out a HTTP error 405 method Not Allowed.
Use query To process requests
ordinary query /api/query?param1=a¶m2=b
export default defineEventHandler((event) => {
const query = useQuery(event)
return { a: query.param1, b: query.param2 }
})
Get the configuration of the runtime
export default defineEventHandler((event) => {
const config = useRuntimeConfig()
return { key: config.KEY }
})
Obtain requested cookie
export default defineEventHandler((event) => {
const cookies = useCookies(event)
return { cookies }
})
Advanced usage example
Use nested routing
import { createRouter } from 'h3'
const router = createRouter()
router.get('/', () => 'Hello World')
export default router
Sending data streams ( Experimental stage )
Be careful : It's an experimental feature , Only in Nodejs Use in the environment .
import fs from 'node:fs'
import { sendStream } from 'h3'
export default defineEventHandler((event) => {
return sendStream(event, fs.createReadStream('/path/to/file'))
})
Return to a traditional handler or middleware
export default (req, res) => {
res.end('Legacy handler')
}
Use unjs/h3 Can support traditional support , But it suggests that you avoid using traditional methods as much as possible .
export default (req, res, next) => {
console.log('Legacy middleware')
next()
}
Never will next() Callback and async Or return Promise With traditional middleware .
边栏推荐
- 小说里的编程 【连载之十八】元宇宙里月亮弯弯
- Diabetes genetic risk testing challenge advanced
- Programming in the novel [serial 18] the moon bends in the yuan universe
- [problem handling] merge made by the 'ort' strategy
- VIM common shortcut keys
- [acwing] weekly competition
- Merge.Avhd into.Vhd manually in Hyper-V
- MySQL的JDBC编程
- Zhongbang technology devotes itself to another work -- gyro maker OA system
- Extract any page number in PDF file with itextpdf
猜你喜欢

zk 是如何解决脑裂问题的

At the forefront of the times, Huawei aims at the wind and sea of digital finance

MVVM和MVVMLight简介及项目开发(一)

Yolo7 mask recognition practice

As a developer, you have to know the three performance testing tools JMeter, API and jmh user guide

STM32单片机使用ADC功能驱动手指检测心跳模块
![[jailhouse article] a novel software architecture for mixed criticality systems (2020)](/img/ab/b9269acfa5135fdaa3d0d8cc052105.png)
[jailhouse article] a novel software architecture for mixed criticality systems (2020)
思源笔记的字体比其他的编辑器(Atom,VSC,sublime)内字体渲染更细更淡

D1-h development board - Introduction to Nezha development
The font of Siyuan notes is thinner and lighter than that in other editors (atom, VSC, sublime)
随机推荐
Extract any page number in PDF file with itextpdf
Getting started database days2
Video Number strengthens the fight against vulgar content: the content that violates public order and good customs must be eliminated
Notes on network segment CIDR
MySQL的JDBC編程
【golang学习笔记】flag包的简单使用,命令行解析
年化收益率6%的理财产品
【golang学习笔记】并发基础
Investment suggestions for overseas senior players (2) 2021-05-03
Programming in the novel [serial 17] the moon bends in the yuan universe
[acwing] weekly competition
121. The best time to buy and sell stocks
synthesizable之Verilog可不可综合
Mongodb - Introduction to the usage of logical operators not, and, or, nor in query statements
Data sorting and usage before torchvision.datasets.imagefolder
使用itextpdf提取PDF文件中的任意页码
vip股票账户在手机开通安全吗?
How to reasonably estimate the size of thread pool
SOLIDWORK learning notes: Sketch geometric relationships and editing
Upgrade unity visual studio 2019 to 2022 (throw away pirated red slag)