koa执行get请求
时间: 2023-09-23 12:05:38 浏览: 46
在Koa中执行GET请求非常简单,你可以使用`ctx.request`对象来访问请求信息,并使用`ctx.response`对象来发送响应。以下是一个简单的示例演示如何执行GET请求:
```javascript
const Koa = require('koa');
const app = new Koa();
app.use(async (ctx) => {
// 获取请求路径
const url = ctx.request.url;
// 获取请求参数
const query = ctx.request.query;
// 发送响应
ctx.response.body = {
url,
query,
};
});
app.listen(3000, () => {
console.log('Server started on port 3000');
});
```
在上面的例子中,我们使用了`ctx.request.url`来获取请求的路径,使用`ctx.request.query`来获取查询参数。然后,我们将这些信息作为响应的主体发送回客户端。
你可以通过在浏览器中访问 http://localhost:3000/?name=John&age=25 来测试这个示例。你将会看到以下响应:
```json
{
"url": "/",
"query": {
"name": "John",
"age": "25"
}
}
```
这是一个简单的示例,你可以根据你的实际需求对路由和处理程序进行进一步的定制。