IT박스

Backbone.js REST 호출 이해

itboxs 2020. 10. 13. 07:35
반응형

Backbone.js REST 호출 이해


Backbone.js 동기화 방법을 이해하려고 노력 중이며 http://backbonejs.org/#Sync 의 문서를 살펴보고있었습니다.

그것은 말한다

The default sync handler maps CRUD to REST like so:

create → POST   /collection
read → GET   /collection[/id]
update → PUT   /collection/id
delete → DELETE   /collection/id

이제 저는 항상 프론트 엔드 개발에 있었고 Backbone을 처음 사용했기 때문에 위의 내용을 이해하기가 어렵습니다 ... REST 또는 다른 서버 측 프로토콜을 사용한 적이 없습니다 ...

(Backbone.sync를 사용할 때 REST가 매핑되는 방식과 같은) 간단한 용어로 동일하게 설명해 주시겠습니까? 아주 간단한 예는 매우 유용 할 것입니다.


괜찮으 시다면, 몇 가지 문구를 정리하는 것으로 시작하겠습니다. REST는 그 자체로 프로토콜이 아니라 단순히 HTTP 프로토콜을 사용하는 방법입니다. REST 스타일은 특히 API에 유용합니다. API가 해당 스타일을 준수하면 "RESTful"이라고합니다. 작업중인 API가 RESTful이 아닌 경우 작동하도록하려면 Backbone.sync를 많이 변경해야합니다. 그래서 바라건대! :)

HTTP 프로토콜

저는 예제를 좋아하므로이 페이지의 HTML을 가져 오는 HTTP 요청이 있습니다.

GET /questions/18504235/understand-backbone-js-rest-calls HTTP/1.1
Host: stackoverflow.com

[선택 사항] 명령 줄이나 터미널을 사용해 본 적이 있다면 명령을 실행 telnet stackoverflow.com 80하고 위의 내용을 붙여 넣은 다음 Enter 키를 몇 번 누릅니다. 짜잔! HTML은 모두 영광입니다.

이 예에서 ...

  • GET는 IS 방법 .
  • /questions/18504235/understand-backbone-js-rest-calls는 IS 경로 .
  • HTTP/1.1는 IS 프로토콜 .
  • Host: stackoverflow.com헤더 의 예입니다 .

이 페이지에 대한 HTML을 얻기 위해 브라우저는 더 많은 헤더를 사용하여 거의 동일합니다. 멋지죠?

프런트 엔드에서 작업하기 때문에 양식 태그를 여러 번 보셨을 것입니다. 다음은 하나의 예입니다.

<form action="/login" method="post">
    <input type="text" name="username" />
    <input type="password" name="password" />
    <input type="submit" name="submit" value="Log In" />
</form>

이 양식을 적절한 데이터와 함께 제출하면 브라우저는 다음과 같은 요청을 보냅니다.

POST /login HTTP/1.1
Host: stackoverflow.com

username=testndtv&password=zachrabbitisawesome123&submit=Log%20In

이전 예제와이 예제에는 세 가지 차이점이 있습니다.

  1. 방법은 지금이다 POST.
  2. 경로는 지금이다 /login.
  3. body 라는 추가 라인이 있습니다 .

다른 방법의 무리가 있지만, 편안하고 응용 프로그램에서 사용하는 사람은 POST, GET, PUT,와 DELETE. 이것은 모든 것에 대해 다른 경로를 가질 필요없이 데이터에 대해 어떤 유형의 조치를 취해야하는지 서버에 알려줍니다.

백본으로 돌아 가기

이제 HTTP 작동 방식에 대해 조금 더 이해했으면합니다. 그러나 이것이 Backbone과 어떤 관련이 있습니까? 알아 보자!

다음은 백본 애플리케이션에서 찾을 수있는 작은 코드 덩어리입니다.

var BookModel = Backbone.Model.extend({
    urlRoot: '/books'
});
var BookCollection = Backbone.Collection.extend({
    model: BookModel
    , url: '/books'
});

만들기 (POST)

RESTful API를 사용하고 있기 때문에 Backbone이 모든 도서 정보를 생성, 읽기, 업데이트 및 삭제할 수 있어야하는 모든 정보입니다! 새 책을 만드는 것부터 시작하겠습니다. 다음 코드로 충분합니다.

var brandNewBook = new BookModel({ title: '1984', author: 'George Orwel' });
brandNewBook.save();

Backbone은 새 책 만들 려고한다는 것을 인식 하고 다음 요청을하기 위해 제공된 정보를 통해 알고 있습니다.

POST /books HTTP/1.1
Host: example.com

{"title":"1984","author":"George Orwel"}

읽기 (GET)

얼마나 쉬웠는지 보셨나요? 그러나 우리는 어느 시점에서 그 정보를 되찾고 싶습니다. 를 실행했다고 가정 해 보겠습니다 new BookCollection().fetch(). 백본은 당신이하려는 것을 이해할 읽어 수집 책, 그리고 다음과 같은 요청을 만들 것입니다 :

GET /books HTTP/1.1
Host: example.com

BAM. 그렇게 쉽습니다. 그러나 우리는 한 권의 책에 대한 정보 만 원한다고 가정 해보십시오. 책 # 42를 가정 해 봅시다. 우리가 달렸다고 해 new BookModel({ id: 42 }).fetch(). 백본은 당신이하려는보고 읽을 하나의 책을 :

GET /books/42 HTTP/1.1
Host: example.com

업데이트 (PUT)

오, 방금 오웰 씨 이름 철자가 틀렸다는 걸 깨달았어요 쉽게 고칠 수 있습니다!

brandNewBook.set('author', 'George Orwell');
brandNewBook.save();

Backbone is smart enough to know that despite being called brandNewBook, it's already been saved. So it updates the book:

PUT /books/84 HTTP/1.1
Host: example.com

{"title":"1984","author":"George Orwell"}

Delete (DELETE)

Finally, you realize that the government is tracking your every move, and you need to bury the fact that you have read 1984. It's probably too late, but it never hurts to try. So you run brandNewBook.destroy(), and Backbone becomes sentient and realizes your danger deletes the book with the following request:

DELETE /books/84 HTTP/1.1
Host: example.com

And it's gone.

Other Useful Tidbits

While we've talked a lot about what we're sending TO the server, we should probably also take a look at what we're getting back. Let's return to our collection of books. If you remember, we made a GET request to /books. In theory, we should get back something like this:

[
    {"id":42,"author":"Douglas Adams","title":"The Hitchhiker's Guide to the Galaxy"}
    , {"id":3,"author":"J. R. R. Tolkien","title":"The Lord of the Rings: The Fellowship of the Ring"}
]

Nothing too scary. And even better, Backbone knows how to handle this out of the box. But what if we changed it a bit? Instead of id being the identifying field, it was bookId?

[
    {"bookId":42,"author":"Douglas Adams","title":"The Hitchhiker's Guide to the Galaxy"}
    , {"bookId":3,"author":"J. R. R. Tolkien","title":"The Lord of the Rings: The Fellowship of the Ring"}
]

Backbone gets that every API is a bit different, and it's okay with that. All you have to do is let it know the idAttribute, like so:

var BookModel = Backbone.Model.extend({
    urlRoot: '/books'
    , idAttribute: 'bookId'
});

You only have to add that information to the model, since the collection checks the model anyway. So just like that, Backbone understands your API! Even if I don't...

The downside of this is that you have to remember to use bookId in certain cases. For example, where we previously used new BookModel({ id: 42 }).fetch() to load the data about a single book, we would now have to use new BookModel({ bookId: 42 }).fetch().


Hopefully you've found this response informative, and not too unbearably dull. I realize that for many, HTTP protocol and RESTful architecture aren't the most exhilarating subjects, so I tried to spice it up a bit. I may regret that when I read all of this back at a later point, but it's 2AM here, so I'm gonna go ahead and submit this anyway.


Assuming you understand ajax calls (POST, GET, etc to '/collection', etc).

Backbone uses sync to route some Models and Collections methods to REST calls.

model/collection.fetch() => GET
model.save() => POST (isNew())
model.save() => PUT (!isNew())
model.destroy() => DELETE

collection.create() calls model.save() (isNew()) => POST

If you pass the url (/collection) you want to use to a model/collection, Backbone will take care of the calls.

참고URL : https://stackoverflow.com/questions/18504235/understand-backbone-js-rest-calls

반응형