Skip to content

Latest commit

 

History

History
111 lines (75 loc) · 2.2 KB

004005-view.md

File metadata and controls

111 lines (75 loc) · 2.2 KB

�View

實作前端串接,透過 api 取得特定 user 之所有 task list 資料

���根據測試案例 API 的定義:

  
  it('透過 api 取得特定 user 之所有 task list 資料', async function () {
    // 建立測試資料
    let username = 'johndoe';
    let user = await this.models.User.create({
      username
    });
    
    await this.models.Task.create({
      title: 'johndoe task',
      UserId: user.id
    });

    // 呼叫 API 取得資料
    let response = await request(app).get(`/api/users/${username}/tasks`);
    let result = response.body;

    // 確認資料結構
    expect(result.tasks).to.be.an('array');
    expect(result.tasks[0])
      .to.be.an('object')
      .and.to.have.property("title");
  });

���```

撰寫對應的前端串接如下

相關檔案路徑

�`${project_home}/express-example-vue/src/components/TodoList.vue`

async mounted () {

let response = await fetch("http://localhost:3000/api/users/hellojs/tasks");
let result = await response.json();

result.tasks.forEach((task) => {
  this.todos.push(task);
});

},


## 實作前端串接,透過 api 新增特定 user 之 task 資料

���根據上一章節 測試案例 API 的定義:

it('透過 api 新增特定 user 之 task 資料', async function () {

// 建立測試資料
let username = 'andy';
await this.models.User.create({
  username
});

let taskData = {
  title: "andy task"
}

// 呼叫 API 新增 task
let response = await request(app)
  .post(`/api/users/${username}/tasks/create`)
  .send(taskData);
let result = response.body;

// 確認資料結構
expect(result.task)
  .to.be.an('object')
  .and.to.have.property("title");

});


撰寫對應的前端串接如下

async addTodo (title) {
  let data = {
    title,
    completed: false
  }

  let response = await fetch('http://localhost:3000/api/users/hellojs/tasks/create', {
    method: 'post',
    headers: {"Content-Type": "application/json"},
    body: JSON.stringify(data)
  });

  let result = await response.json();

  this.todos.push(result.task)
    
}