在實習期間,因為公司需要,必須搭建一個Web API,上網查了一下之後發現Nodejs & express 搭配是個不錯的做法,於是買了本Nodejs的書翻了幾天,上網找了一些資料之後就開始著手了,這篇是自己在建置過程的筆記。

裡面有許多的內容是參考這篇:

Build a RESTful API Using Node and Express4

有興趣的人可以連結至原文觀看。

目標

  • 利用HTTP方法 GET POST PUT DELET 搭建基礎RESTful API。
  • 回傳json格式的資料。

關於RESTful API,這篇有更詳細的介紹:

Designing a RESTful Web API

開始

本文預設你已經裝好了Nodejs & express4。

一、 建立一個express專案

我是利用express generator來建立,如果尚未安裝,請先打開你的終端機,輸入npm install -g express-generator,等安裝好之後,就可以利用express yourapp這項指令來建立專案。

假設這個API專案的名稱為node-api,輸入以下指令:

$ express node-api

就會在該目錄下產生一資料夾為node-api。

二、安裝相依套件

進入目錄,安裝相關套件:

$ cd node-api
$ npm install

三、建立自己的API檔

在routes資料夾下建立apis.js,打開之後輸入以下內容:

apis.js
var express = require('express');
var router = express.Router();

route.get('/images', function(req, res) {
    res.json({ message: "第一個API!" });
});

module.exports = router;

之後打開app.js,在第10行與第26行分別加入以下內容(其實加在哪裡都沒差,只是require跟app.use分開放比較整齊):

app.js
var apis = require('./routes/apis'); // 加在require部分


app.use('/api', apis); // 加在app.use部分

打開terminal,輸入

$ npm start

server就跑起來囉,預設的port為 http://localhost:3000

四、測試API(利用Postman)

api寫好也跑起來之後,就可以來進行測試囉。Postman是一款簡單易用的工具,它可以幫你送出不同的HTTP方法到某個網址,也可以讓你輸入參數。

打開Postman,輸入http://localhost:3000/api/images,選get,就可以看到如下的畫面

恭喜你,完成了最基礎的api!

五、單筆資料的CRUD

接下來就是搭建針對單筆資料CRUD的RESTful api;與上一個做法不同的地方是,在網址部分傳入id當作參數(本文中不會實作資料庫的部分,僅僅是搭建一個架構,如果需要更進一步了解api與資料庫的搭配,可以參考開頭的那篇連結)。

api.js內輸入以下內容:

api.js
router.route('/images/:id') // 輸入id當作參數


.get(function(req, res) {
    res.json({
        id: req.params.id, // 以req.params.id 取得參數

        message: 'The get api for image: ' + req.params.id
    })
})

.post(function(req, res) {
    res.json({
        id: req.params.id,
        message: 'The post api for image: ' + req.params.id
    })
})

.put(function(req, res) {
    res.json({
        id: req.params.id,
        message: 'The put api for image: ' + req.params.id
    })
})

.delete(function(req, res) {
    res.json({
        id: req.params.id,
        message: 'The delete api for image: ' + req.params.id
    })
});

之後,同樣利用Postman,選擇不同的HTTP method來進行檢視。以下以post為例:

到此就完成了基本api的雛形,接下來就可以針對不同的method來進行CRUD的實作囉。

前言:

學ROR已經有一段時間了,不過還真沒有好好的學過一遍Ruby。
過年期間稍微看過一遍Learn to Program,不過真的是稍微瀏覽,
沒有實際動手去弄,這次一定要每天做一點點啊...不能再廢了!

以下就記錄一下每天的心得。

1. 如何知道require lib的路徑:

在command line中輸入 ruby -e 'puts $:'

2. exercise13中,STDIN.gets 與一般gets的不同

在Learn Ruby The Hard Way中如此解釋:

Important: Also notice that we're using STDIN.gets instead of plain 'ol gets. That is because if there is stuff in ARGV, the default gets method tries to treat the first one as a file and read from that. To read from the user's input (i.e., stdin) in such a situation, you have to use it STDIN.gets explicitly.
簡單來說,gets是kernal#gets(待解),會先去讀取ARGV參數給予的檔案,如果沒有給予,則會轉回standard input(即STDIN),故在這一個練習中必須使用STDIN,因為在有ARGV的情況下,gets會先去尋找第一個參數的檔案。
ex.
ex13.rb first second third
則gets會去找是否有first這檔案,沒有的話則會拋出error,範例如下:

ex13.rb
first, second, third = ARGV
puts "The script is called #{$0}." # $0 present for the script name. ex. ex13.rb

puts "First variable is #{first}."
puts "Second variable is #{second}."
puts "Third variable is #{third}."
fourth = STDIN.gets.chomp() 
# 如果使用gets,則會去抓first的ARGV,查看是否有**檔案**符合(注意:是檔案不是變數)

puts "The forth variable by STDIN.gets is #{fourth}."

3. exercise 16的加分題:

difference between method and funtion:

A method is on an object.
A function is independent of an object.

For Java, there are only methods.
For C, there are only functions.
For Ruby, there are only methods.

For C++ it would depend on whether or not you're in a class.

4. exercise 20 關於File中的seek函數

在ex20中提到file.seek(offset, IO::SEEK_SET)
第二個餐數有 IO::SEEK_SET IO::SEEK_CUR IO::SEEK_END
目的都是用來將指標指向文件中指定的位置,三者代表的意義如下
SEEK_SET: 指向offset所指定的位置(從0開始)
SEEK_CUR: 指向當前位置加上offset值後的位置
SEEK_END: 指向offset所指定位置,從文字最後面開始(offset須用負數)

SET與END應該都不難理解,來看一下CUR
範例:

seek.rb
file = File.open(foo.txt)
file.readline() # 讀完第一行,此時指標會在第二行開頭

file.seek(1, IO::SEEK_CUR) # 指標指向第二個字

file.readline() # 由第二行第二個字印出

5. class中method self的使用

在class中,method如果使用self, 則為class method, 如果沒有, 則為instance method,舉例如下

class_method_and_instance_method.rb
class Foo
  def bar
    puts "Here is bar, an instance method."
  end
  
  def self.baz
    puts "Here is baz, an class method."
  end
end

Foo.bar # => undefined method `baz' for #<Foo:0x007fdf5a04bf78> (NoMethodError)

Foo.baz # => "Here is baz, an class method."


Foo.new.bar # => "Here is bar, an instance method."

Foo.new.baz # => undefined method `baz' for #<Foo:0x007fdf5a04bf78> (NoMethodError)

Actually, this is my homework, I tried to record the step for how I resolve this issue.

I had read some articles and tried many ways(include heroku official document),
but it didn't work.

So I tried to read amazon official document and did some settings myself. Finally,
it works fine.

following are my steps:
(I assume that your app have already run well on heroku)

first, add this gem to your gemfile:

Gemfile
gem 'aws-sdk'

bundke install

add aws.yml under config folder:

aws.yml
development:

  access_key_id: your access key id

  secret_access_key: your secret access key


production:

  access_key_id: your access key id

  secret_access_key: your secret access key

then restart your rails server(for local test)

model action:

photo.rb
has_attached_file :image, :styles => { :medium => "300x300>",
                                       :small => "150x150",
                                       :thumb => "100x100>" },
                          :storage => :s3, 
                            :s3_protocol => 'http', 
                            :s3_host_name => 'your host name',
                            :bucket => 'bucket name'

Done! Paperclip will save your images on amazon s3 automatically!

  1. Open terminal.

  2. Switch to the heroku app repository which name you want to change.

  3. Type: heroku apps:rename your-new-appname (Name must start with a letter and can only contain lowercase letters, numbers, and dashes.)

  4. Then type: heroku open to open your app.

  5. You will see your url become https://your-new-appname.herokuapp.com/ on your web browser.

  6. Done!

Notice! After change the appname, your old app url will become unavailable.

This article is referenced from stackoverflow:

If installed PostgreSQL with homebrew , enter brew uninstall postgresql

If you used the EnterpriseDB installer , follow the following step.

Run the uninstaller on terminal window

sudo /Library/PostgreSQL/9.X/uninstall-postgresql.app/Contents/MacOS/installbuilder.sh

If installed with Postgres Installer, do:

open /Library/PostgreSQL/9.X/uninstall-postgresql.app

Remove the PostgreSQL and data folders. The Wizard will notify you that these were not removed.

sudo rm -rf /Library/PostgreSQL

Remove the ini file:

sudo rm /etc/postgres-reg.ini

Remove the PostgreSQL user using System Preferences -> Users & Groups.

  1. Unlock the settings panel by clicking on the padlock and entering your password.
  2. Select the PostgreSQL user and click on the minus button.
  3. Restore your shared memory settings: sudo rm /etc/sysctl.conf