2

我正在尝试使用json-server构建快速后端

我的端点和数据如下:

端点:http://localhost:3000/members/1

输出数据:

在此处输入图像描述

现在假设我想做几件事,比如:

  1. 获取成员的所有报告。

按照文档,我试图做: http://localhost:3000/members/1?_embed=reports获取reports数组。但这是对我空数组的回应:

{
id: 1,
username: "member1",
firstName: "Miss Osbaldo",
lastName: "Wisozk",
password: "123456",
role: "member",
reports: [ ]
}
  1. 我想将一些report对象添加到reports数组中。我怎样才能做到这一点?

例如id=1创建新报告的成员。之后该报告应该存在于reports成员 1 的数组中。

我的generates.js文件:

return {
members: _.times(30, function (n) {
  return {
    id: (n + 1),
    username: 'member' + (n + 1),
    firstName: faker.name.prefix() + ' ' + faker.name.firstName(),
    lastName: faker.name.lastName(),
    avatar: faker.image.avatar(),
    address: faker.address.streetAddress("###") + ' ' + faker.address.city() + ' ' + faker.address.county(),
    phone: faker.phone.phoneNumberFormat(),
    division: faker.random.arrayElement(division),
    password: "123456",
    role: "member",
    reports: _.times(5, function (n) {
      return {
        id: n,
        date: faker.date.weekday(),
        achievement: faker.lorem.sentence(),
        issues: faker.random.arrayElement(issues),
        descriptions: faker.lorem.paragraphs(),
        comment: faker.lorem.sentences()
      }
    })
  }
}),
4

3 回答 3

0

分贝 = {}

db.posts = [
  { id: 1, body: 'foo' },
  { id: 2, body: 'bar' },
]

db.comments = [
  { id: 1, post_id: 1 },
  { id: 2, post_id: 1 },
  { id: 3, post_id: 2 },
]

server = jsonServer.create()
router = jsonServer.router(db, { foreignKeySuffix: '_id' })
server.use(jsonServer.defaults())
server.use(router)

})

于 2021-02-06T12:02:55.790 回答
0

对于您的问题#1,请使用http://localhost:3000/members/1/reports路线。它将返回成员 #1 的所有报告

于 2018-07-05T04:58:21.987 回答
0

根据文档现场演示,您的第一个请求/查询是正确的:http://jsonplaceholder.typicode.com/posts/1?_embed=comments返回帖子 #1 及其所有评论。

对于您的问题 #1,我建议您仔细检查您的数据库文件。

对于第二个问题,您可以使用 POST 和 PATCH 等 HTTP 动词:https ://github.com/typicode/jsonplaceholder#updating-a-resource 这应该更新您的“数据库”文件(json 文件)

于 2018-07-05T03:56:22.003 回答