HTTP的options方法作用
1.HTTP的options方法作用
- 检测服务器所支持的请求方法。(比如:‘/user'路由支持哪些方法:get、post、delete...)
- CORS中的预检请求(检测某个接口是否支持跨域)
2.allowedMethods方法
- 响应options方法,告诉它所支持的请求方法
- 相应的返回405(不允许)和501(没实现)(比如我使用delete,会返回405,因为我没有写这个接口。但我使用link接口请求,会返回501,因为koa里不支持link请求)
3.实现方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | const Koa = require( 'koa' ); const Router = require( 'koa-router' ); const app = new Koa(); const router = new Router(); const userRouter = new Router({prefix: '/user' }) router. get ( '/' ,(ctx)=>{ ctx.body = "这是主页!" }) userRouter. get ( '/' ,(ctx)=>{ ctx.body = "这是get!" }) userRouter.post( '/' ,(ctx)=>{ ctx.body = "这是post!" }) userRouter. get ( '/:id' ,(ctx)=>{ ctx.body = `这是${ctx. params .id}` }) app.use(router.routes()) //把router注入app app.use(userRouter.routes()) //把router注入app <strong>app.use(userRouter.allowedMethods()) //用来相应options方法。</strong> app.listen(3000) |
这时使用options方法请求,结果如下:这个接口支持get和post方法。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步