MST

星途 面试题库

面试题:Ruby 中如何实现 Web 服务的路由功能

在使用 Ruby 进行 Web 服务开发时,例如使用 Sinatra 框架,简述如何定义不同的路由来处理不同的 HTTP 请求,比如 GET、POST 请求,并举例说明如何在路由处理函数中返回合适的数据给客户端。
15.6万 热度难度
编程语言Ruby

知识考点

AI 面试

面试题答案

一键面试
  1. 使用Sinatra定义GET路由
    • 在Sinatra中,使用get关键字定义处理GET请求的路由。
    • 示例代码:
require'sinatra'

get '/' do
  "This is the response for the root GET request."
end
  • 上述代码定义了一个处理根路径(/)的GET请求的路由,当客户端发起对根路径的GET请求时,会返回字符串This is the response for the root GET request.
  1. 使用Sinatra定义POST路由
    • 使用post关键字定义处理POST请求的路由。
    • 示例代码:
require'sinatra'

post '/submit' do
  # 假设POST请求提交了表单数据,这里获取表单中的name字段
  name = params[:name]
  "Hello, #{name}! This is the response for the POST request at /submit."
end
  • 上述代码定义了一个处理/submit路径的POST请求的路由。它从POST请求的参数(假设是表单数据)中获取name字段,并返回包含该名字的响应。
  1. 返回不同类型的数据给客户端
    • 返回JSON数据
require'sinatra'
require 'json'

get '/data' do
  content_type :json
  data = { message: 'This is JSON data', value: 42 }
  data.to_json
end
  • 上述代码定义了一个处理/data路径的GET请求的路由,设置响应的内容类型为application/json,并将一个Ruby哈希转换为JSON格式的字符串返回给客户端。
  • 返回HTML数据
require'sinatra'

get '/html' do
  content_type :html
  "<html><body><h1>这是一个HTML响应</h1></body></html>"
end
  • 此代码定义了一个处理/html路径的GET请求的路由,设置响应的内容类型为text/html,并返回一段HTML代码作为响应。