jsonserver(jsonserver官网)

简介:

JSON Server是一个Node.js包,可以帮助开发人员搭建快速的本地RESTful API。

多级标题:

1. 安装JSON Server

2. 创建一个简单的API

3. 使用默认资源

4. 设定自定义路由

5. 嵌套资源

6. 启用中间件

7. 认证和授权

内容详细说明:

1. 安装JSON Server

首先,你需要在你的项目目录中安装JSON Server,可以使用npm进行安装。

```

npm install -g json-server

```

2. 创建一个简单的API

接下来,我们可以创建一个简单的API。在你的项目文件夹中,创建一个JSON文件,例如db.json,并在其中添加一些数据:

```

"products": [

{ "id": 1, "name": "iPhone X", "price": 999 },

{ "id": 2, "name": "Samsung Galaxy S9", "price": 899 },

{ "id": 3, "name": "Google Pixel 2", "price": 749 }

]

```

3. 使用默认资源

现在,我们可以使用JSON Server将db.json转换为RESTful API。在命令行中运行以下命令:

```

json-server --watch db.json

```

这将启动JSON Server,并将API暴露在http://localhost:3000上。现在,我们可以使用GET命令获取所有产品:

```

GET http://localhost:3000/products

```

4. 设定自定义路由

JSON Server不仅可以自动生成默认的路由,还可以实现自定义路由。我们可以在db.json中添加路由属性:

```

"routes": {

"/api/products/:id": "/products/:id"

},

"products": [

{ "id": 1, "name": "iPhone X", "price": 999 },

{ "id": 2, "name": "Samsung Galaxy S9", "price": 899 },

{ "id": 3, "name": "Google Pixel 2", "price": 749 }

]

```

现在,我们可以使用以下URL获取指定的产品:

```

GET http://localhost:3000/api/products/1

```

5. 嵌套资源

我们甚至可以通过嵌套资源来实现更高级的功能。例如,我们可以向db.json中添加一个订单和订单详情:

```

"orders": [

{ "id": 1, "customer": "John Doe", "items": [ { "product": 1, "quantity": 2 } ] }

],

"orderDetails": [

{ "orderId": 1, "product": 1, "price": 999, "quantity": 2 }

],

"products": [

{ "id": 1, "name": "iPhone X", "price": 999 },

{ "id": 2, "name": "Samsung Galaxy S9", "price": 899 },

{ "id": 3, "name": "Google Pixel 2", "price": 749 }

]

```

现在,我们可以使用以下URL获取一个订单及其细节:

```

GET http://localhost:3000/orders/1?_embed=orderDetails

```

6. 启用中间件

JSON Server还支持使用中间件来拦截和修改请求。我们可以在启动JSON Server时添加中间件:

```

const jsonServer = require('json-server')

const server = jsonServer.create()

const router = jsonServer.router('db.json')

const middlewares = jsonServer.defaults()

server.use(middlewares)

server.use(jsonServer.bodyParser)

server.post('/products', function (req, res, next) {

const error = validateProduct(req.body)

if (error) {

res.status(400).send(error)

} else {

req.body.id = Math.floor(Math.random() * 100)

next()

}

})

server.use(router)

server.listen(3000, () => {

console.log('JSON Server is running')

})

```

现在,我们定义了一个POST路由,会对新创建的产品进行验证。如果验证失败,则返回400错误;否则,将在请求主体中添加一个随机ID。

7. 认证和授权

最后,我们可以使用JSON Server支持的身份验证和授权来保护我们的API。JSON Server默认不提供身份验证和授权,但是可以通过添加自定义中间件来实现它们。

```

server.use((req, res, next) => {

if (req.headers.authorization) {

const [type, token] = req.headers.authorization.split(' ')

if (type === 'Bearer' && token === 'my-secret-token') {

next()

} else {

res.sendStatus(401)

}

} else {

res.sendStatus(401)

}

})

```

现在,我们定义了一个中间件,检查请求头是否包含授权标头。如果标头有效,则继续下一个中间件;否则,返回401错误。

总结:

JSON Server是一个非常有用的工具,可以快速搭建本地RESTful API,提高开发效率。它支持许多高级功能,如自定义路由和嵌套资源,并且可以使用中间件来扩展和保护API。

Powered By Z-BlogPHP 1.7.2

备案号:蜀ICP备2023005218号