当前位置:网站首页>[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 .
边栏推荐
- Life always needs a little passion
- How to reasonably estimate the size of thread pool
- 小说里的编程 【连载之十七】元宇宙里月亮弯弯
- [in depth study of 4g/5g/6g topic -40]: urllc-11 - in depth interpretation of 3GPP urllc related protocols, specifications and technical principles -5-5g QoS principle and Architecture: slicing, PDU s
- Preparation for raspberry pie 3B serial port login
- 【golang学习笔记】Go语言中参数的传递是值传递还是引用传递
- 1000 okaleido tiger launched binance NFT, triggering a rush to buy
- Internet协议栈 TCP/IP模型 物理层、链路层、网络层、传输层、应用层的作用
- openEuler 资源利用率提升之道 01:概论
- D1-h development board - Introduction to Nezha development
猜你喜欢
思源笔记的字体比其他的编辑器(Atom,VSC,sublime)内字体渲染更细更淡

Still worrying about xshell cracking, try tabby

What else do entrepreneurs need besides money? Exclusive interview with Mingyue Lake venture capital institutions

Microsoft SQL Server数据库语言及功能使用(十三)
![[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)

Matlab小波工具箱导入信号出错(doesn‘t contain one dimensional Singal)

Investment suggestions for overseas senior players (2) 2021-05-03

After reading this article, thoroughly understand grpc!

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
QT set cache and compile output path
Wangxuegang video coding -- mediacodec coding and decoding
[problem handling] merge made by the 'ort' strategy
fl studio 20.9更新中文版宿主DAW数字音频工作站
Mongodb - Introduction to the usage of logical operators not, and, or, nor in query statements
人生总需要一点激情
DeFi项目的盈利逻辑 2021-04-26
Financial products with an annual yield of 6%
众邦科技又一潜心力作 —— 陀螺匠 OA 系统
Utilisation des fonctions fléchées es6
El upload realizes the preview of uploaded files
STM32+ESP8266+MQTT协议连接阿里云物联网平台
[laser principle and Application-8]: EMC design of laser circuit
Explain NAT technology in detail
Matlab小波工具箱导入信号出错(doesn‘t contain one dimensional Singal)
Leetcode high frequency question 62. different paths: how many paths does the robot have from the upper left corner to the lower right corner? Pure probability permutation and combination problem, not
Neo4j application
13. Roman to integer
Upgrade unity visual studio 2019 to 2022 (throw away pirated red slag)