以blogs 的脚手架和rails routes (rake routes) 为例,您可以看到在routes.rb 中定义的所有“端点”:
Prefix Verb URI Pattern Controller#Action
blogs GET /blogs(.:format) blogs#index
POST /blogs(.:format) blogs#create
new_blog GET /blogs/new(.:format) blogs#new
edit_blog GET /blogs/:id/edit(.:format) blogs#edit
blog GET /blogs/:id(.:format) blogs#show
PATCH /blogs/:id(.:format) blogs#update
PUT /blogs/:id(.:format) blogs#update
DELETE /blogs/:id(.:format) blogs#destroy
如果您看到 blogs GET /blogs(.:format) blogs#index 正在通过 GET 请求为您提供所有 blogs。
这应该会为您带来 API 中的所有 blogs:
使用纯 Javascript
var request = new XMLHttpRequest();
request.open('GET', 'localhost:3000/blogs', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
var data = JSON.parse(request.responseText)
...
} else {
...
}
};
request.onerror = function() {
...
};
request.send();
同样使用 Javascript fetch:
fetch('localhost:3000/blogs', {
...
}).then(function(response) {
console.log(response)
}).catch(function(err) {
console.log(err)
});
使用 jQuery:
$.ajax({
url: 'localhost:3000/blogs',
dataType: 'script',
success: function(result) {
console.log(result)
},
});
然后您可以根据需要继续插入、更新和/或删除数据。