Skip to content

Home

使用Express設置代理伺服器

問題:

我正在進行一個使用BreweryDB的項目。在嘗試從API加載一些數據時,我遇到一個問題:該API不支援JSONP。當我試圖直接使用Angular獲取數據時,會導致CORS問題:

XMLHttpRequest無法加載[https://api.brewerydb.com/v2/.](https://api.brewerydb.com/v2/)。請求的資源上沒有'Access-Control-Allow-Origin'頭。因此,不允許“http://localhost:3000”的來源訪問。

我的解決方案:

為了避免暴露我的API密鑰,我需要設置一個中間代理。以下是使用Node.js和Express設置代理的步驟說明。

步驟1:安裝Express和Request

npm install express --save
npm install request --save

步驟2:建立一個 server.js 檔案

var express = require('express');
var request = require('request');
var app = express();

步驟3:設定路由(將 API_KEY 換成你實際的API密鑰)

app.get('/api', function(req, res) {
  request('https://api.brewerydb.com/v2/?key=' + API_KEY, function (error, response, body) {
    if (!error && response.statusCode === 200) {
      console.log(body);
      res.send(body);
    }
  });
});

步驟4:設定埠口

app.listen(3000);
console.log('伺服器在埠口%d運行', 3000);

步驟5:啟動伺服器(node server.js

開啟你的瀏覽器,導航到 http://localhost:3000/api 。你應該能看到JSON物件並且在你的瀏覽器控制台中將其記錄下來:

"message": "請求成功",
"data": "您已到達BreweryDB.com API。對於訪問,請查看http://www.brewerydb.com/developers",
"status": "成功"

如果您遇到任何問題,請隨時向我發送電子郵件。☺

Angular UI Bootstrap: Opening the First Accordion with ng-repeat

The Problem:

I was using the accordion directive in Angular UI Bootstrap version 0.1.2. On the demo page, there's an example showing how to open the first accordion group by default:

<accordion-group heading="First Header" is-open="true"> </accordion-group>

This works well for static content but fails to operate as expected with dynamic content generated using ng-repeat. In other words, it does not work like this:

<accordion-group
  heading="{{group.title}}"
  ng-repeat="group in groups"
  is-open="true"
>
</accordion-group>

My Solution:

In the template, bind the is-open property of the accordion as follows:

<accordion-group
  heading="{{group.title}}"
  ng-repeat="group in groups"
  is-open="status.isItemOpen[$index]"
>
</accordion-group>

And in the controller:

$scope.groups = ["First Header", "Second Header", "Third Header"]
$scope.status = {
  isItemOpen: new Array($scope.groups.length),
  isFirstDisabled: false,
}
$scope.status.isItemOpen[0] = true

Change the value of the last line to false if you prefer the first accordion to be closed by default.

Let me know if this doesn't work for you. 😊

Angular UI Bootstrap:使用ng-repeat開啟第一個手風琴

問題:

我在使用Angular UI Bootstrap版本0.1.2的手風琴指令。在示例頁面上,有一個範例顯示如何默認開啟第一個手風琴組:

<accordion-group heading="First Header" is-open="true"> </accordion-group>

這對於靜態內容來說工作得很好,但是對於使用ng-repeat生成的動態內容來說,它無法如預期地操作。換句話說,它不能這樣工作:

<accordion-group
  heading="{{group.title}}"
  ng-repeat="group in groups"
  is-open="true"
>
</accordion-group>

我的解決方案:

在模板中,將手風琴的is-open屬性綁定如下:

<accordion-group
  heading="{{group.title}}"
  ng-repeat="group in groups"
  is-open="status.isItemOpen[$index]"
>
</accordion-group>

並在控制器中:

$scope.groups = ["First Header", "Second Header", "Third Header"]
$scope.status = {
  isItemOpen: new Array($scope.groups.length),
  isFirstDisabled: false,
}
$scope.status.isItemOpen[0] = true

如果你希望第一個手風琴默認為關閉,則將最後一行的值改為false

如果這個解決方案對你沒有作用,請讓我知道。😊

Note on Ionic Framework: Android Platform in OS X

In this blog post, we will walk through several error messages that you might encounter when installing dependencies for the Android platform of the Ionic framework on Mac OS X. Follow this official guide to install Cordova and Ionic, and then create a project up until the step where you configure the platform.

To enable the Android platform, run the following command:

ionic platform add android

However, you may encounter this error:

Error: ANDROID_HOME is not set and "android" command not in your PATH.

Step 1: Download the Android SDK

Visit the Android developer website and download the stand-alone SDK Tools: https://developer.android.com/sdk/installing/index.html.

Step 2: Unzip the File

I unzipped the SDK to the path of my workspace:

/Users/Victor/Workspace/android-sdk-macosx

Step 3: Set the Android Command in Your PATH

Note: Replace "Victor" with your username. If you are using oh-my-zsh, replace the .bash_profile with your .zshrc profile.

  1. Open your terminal and ensure that .bash_profile ends with a newline:
echo >> /Users/Victor/.bash_profile
  1. Set the ANDROID_HOME environment variable in .bash_profile:
echo "export ANDROID_HOME=/Users/Victor/Workspace/android-sdk-macosx" >> /Users/Victor/.bash_profile
  1. Update the PATH variable as well:
echo "export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools" >> /Users/Victor/.bash_profile
  1. Reload the terminal to apply the changes:
. /Users/Victor/.bash_profile

Step 4: Install Android-19

Now, if you try to run:

ionic platform add android

You might see the following error:

Error: Please install Android target "android-19".

Run android from your command line to open the SDK manager:

android

Check the box for Android 4.4.2 (API 19) and then click "Install 8 packages…". Accept the license and keep your fingers crossed while waiting for the download process to complete.

Finally, try running the command again:

ionic platform add android

And voila:

Project successfully created.

If you encounter any issues, feel free to send me a help request. Cheers! ☺

關於Ionic框架的註解:OS X中的Android平台

在這篇博客文章中,我們將一起研究你在Mac OS X上為Ionic框架的Android平台安裝依賴時可能遇到的幾種錯誤信息。請按照這個官方指南來安裝Cordova和Ionic,然後創建一個項目,直到你配置平台的步驟。

要啟用Android平台,請運行以下命令:

ionic platform add android

然而,你可能遇到這個錯誤:

Error: ANDROID_HOME is not set and "android" command not in your PATH.

步驟1:下載Android SDK

訪問 Android 開發者網站並下載獨立的 SDK 工具:https://developer.android.com/sdk/installing/index.html

步驟2:解壓縮文件

我將SDK解壓縮到我的工作空間的路徑:

/Users/Victor/Workspace/android-sdk-macosx

步驟3:在您的PATH中設置Android命令

注意:將"Victor"替換成您的用戶名。如果您使用的是oh-my-zsh,請將.bash_profile替換成您的.zshrc配置文件。

  1. 打開您的終端並確保 .bash_profile 以一個新行結束:
echo >> /Users/Victor/.bash_profile
  1. .bash_profile中設置 ANDROID_HOME 環境變量:
echo "export ANDROID_HOME=/Users/Victor/Workspace/android-sdk-macosx" >> /Users/Victor/.bash_profile
  1. 也更新PATH變量:
echo "export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools" >> /Users/Victor/.bash_profile
  1. 重載終端以應用更改:
. /Users/Victor/.bash_profile

步驟4:安裝Android-19

現在,如果您嘗試運行:

ionic platform add android

您可能會看到以下的錯誤:

Error: Please install Android target "android-19".

從命令行運行 android 打開SDK管理器:

android

勾選 Android 4.4.2 (API 19),然後點擊 "Install 8 packages…”。接受授權並等待下載過程完成。

最後,再次嘗試運行命令:

ionic platform add android

然後就成功了:

Project successfully created.

如果您遇到任何問題,請隨時向我發送幫助請求。幹杯!☺

Configure CircleCI with Karma Test

The Problem

I was setting up continuous integration using CircleCI and Karma tests for Angular on Heroku.

The tests were working on my local host, but Karma was not found on CircleCI:

Uh-oh, some tests have failed!
Failing command: npm test
Exit code: 1
Output:
> karma start karma.conf.js

sh: 1: karma: not found
npm ERR! Test failed. See above for more details.
((npm :test)) returned exit code 1

My Solution

To resolve this issue, either create or edit your circle.yml config file. Add dependencies using npm to install karma-cli globally, and use Bower to install Angular, as shown below:

dependencies:
  pre:
    - npm install -g karma-cli bower
    - bower install
  cache_directories:
    - ~/nvm

This configuration should help you run your Karma tests successfully on CircleCI.

將CircleCI與Karma測試配置

問題

我正在設置使用CircleCI和Karma測試的Angular在Heroku上的持續集成。

![] (./2014-12-22.png)

測試在我的本地主機上可以運行,但在CircleCI上找不到Karma:

噢哦,有些測試沒有通過!
失敗的命令:npm測試
退出代碼:1
輸出:
>啟動 karma karma.conf.js

sh:1:karma:找不到
npm ERR!測試失敗。有關詳細信息,請參見上文。
((npm:test))返回退出代碼1

我的解決方案

要解決這個問題,您可以創建或編輯 circle.yml 配置文件。使用npm添加依賴以全局安裝 karma-cli,並使用Bower安裝Angular,如下所示:

dependencies:
   pre:
     - npm install -g karma-cli bower
     - bower安裝
   cache_directories:
     - ~/nvm

此配置應該可以幫助您在CircleCI上成功運行您的Karma測試。

How to Upload Files with Meteor.js?

NOTE: This tutorial uses Meteor 1.1.3 with cfs:standard-package 0.0.2 as of December 15, 2014. Since this feature is under active development, it may have changed by the time you read this. Feel free to contact me if you have any questions. :)

The Problem

Last week, a friend of mine asked me how to handle file uploads in a Meteor project. I recommended he use Collection FS, and he followed the README.md instructions on their repository. The file upload feature worked fine on localhost but failed once deployed to the free Meteor testing server. In fact, the server would keep refreshing and wouldn't even load a page.

My Explanation

This issue arises because FS.filesystem uploads the image to a public folder directory. Due to security concerns, this is not allowed by the server unless properly configured. A workaround is to use GridFS as a storage adapter to insert images into MongoDB.

My Solution

Installation

First, instead of using cfs:filesystem, use cfs:gridfs for your package.

    meteor add cfs:standard-packages
    meteor add cfs:gridfs
Syntax

Next, when declaring your collection, switch from using FS.Collection to FS.Store.GridFS.

var imageStore = new FS.Store.GridFS("images")

Images = new FS.Collection("images", {
  stores: [imageStore],
})
Permissions

Then, set up 'deny' and 'allow' rules based on your needs.

Images.deny({
  insert: function () {
    return false
  },
  update:
  created: function () {
    return false
  },
  remove: function () {
    return false
  },
  download: function () {
    return false
  },
})

Images.allow({
  insert: function () {
    return true
  },
  update:
  created: function () {
    return true
  },
  remove: function () {
    return true
  },
  download: function () {
    return true
  },
})
User Interface

Add a file input button in your client template for users to click.

<input type="file" name="..." class="myFileInput" />

Handle the event as follows:

Template.Profile.events({
  "change .myFileInput": function (event, template) {
    FS.Utility.eachFile(event, function (file) {
      Images.insert(file, function (err, fileObj) {
        if (err) {
          // handle error
        } else {
          // handle success depending on your needs
          var userId = Meteor.userId()
          var imagesURL = {
            "profile.image": "/cfs/files/images/" + fileObj._id,
          }
          Meteor.users.update(userId, { $set: imagesURL })
        }
      })
    })
  },
})
Publication/Subscription

Lastly, don't forget to set up publication and subscription in case you've removed the autopublish package.

Meteor.publish("images", function () {
  return Images.find()
})

Subscribe to it in your iron:router:

Router.route("/profile", {
  waitOn: function () {
    return Meteor.subscribe("images")
  },
  action: function () {
    if (this.ready()) this.render("Profile")
    else this.render("Loading")
  },
})

I hope this solution works for you. If you're using an Amazon S3 bucket, consider using cfs:s3 as the adapter. If all else fails, Filepicker could serve as an alternative approach for handling file uploads. For more information, visit Filepicker's website.

如何使用Meteor.js上傳檔案?

注意: 本教程使用的是2014年12月15日的Meteor 1.1.3 和 cfs:standard-package 0.0.2。由於此功能正在積極開發中,您閱讀此文時可能已有所變化。如果你有任何疑問,請隨時聯絡我。:)

問題描述

上周,我的一個朋友問我如何在Meteor項目中處理檔案上傳。我建議他使用Collection FS,並按照他們存儲庫的README.md指南。檔案上傳功能在本地主機上工作正常,但一旦部署到免費的Meteor測試服務器,就會失敗。事實上,服務器會不斷刷新,甚至無法加載頁面。

我的解釋

這個問題產生的原因是 FS.filesystem 將圖像上傳到公共資料夾目錄。由於安全考慮,除非經過適當配置,否則服務器不允許這樣做。一個解決方法是使用 GridFS 作為儲存適配器,將圖像插入到MongoDB中。

我的解決方案

安裝

首先,不要使用cfs:filesystem,而要為您的套件使用cfs:gridfs

    meteor add cfs:standard-packages
    meteor add cfs:gridfs
語法

接下來,當聲明您的集合時,從使用 FS.Collection 切換到 FS.Store.GridFS

var imageStore = new FS.Store.GridFS("images")

Images = new FS.Collection("images", {
  stores: [imageStore],
})
權限

然後,根據你的需求設定'deny'和'allow'規則。

Images.deny({
  insert: function () {
    return false
  },
  update:
  created: function () {
    return false
  },
  remove: function () {
    return false
  },
  download: function () {
    return false
  },
})

Images.allow({
  insert: function () {
    return true
  },
  update:
  created: function () {
    return true
  },
  remove: function () {
    return true
  },
  download: function () {
    return true
  },
})
使用者介面

在客戶端模板中添加一個檔案輸入按鈕以供使用者點擊。

<input type="file" name="..." class="myFileInput" />

像這樣處理事件:

Template.Profile.events({
  "change .myFileInput": function (event, template) {
    FS.Utility.eachFile(event, function (file) {
      Images.insert(file, function (err, fileObj) {
        if (err) {
          // handle error
        } else {
          // handle success depending on your needs
          var userId = Meteor.userId()
          var imagesURL = {
            "profile.image": "/cfs/files/images/" + fileObj._id,
          }
          Meteor.users.update(userId, { $set: imagesURL })
        }
      })
    })
  },
})
發佈/訂閱

最後,如果你已經移除了 autopublish 套件,不要忘記設定發佈和訂閱。

Meteor.publish("images", function () {
  return Images.find()
})

在你的 iron:router 中訂閱它:

Router.route("/profile", {
  waitOn: function () {
    return Meteor.subscribe("images")
  },
  action: function () {
    if (this.ready()) this.render("Profile")
    else this.render("Loading")
  },
})

我希望這個解決方案對你有所幫助。如果你正在使用Amazon S3 bucket,可以考慮使用 cfs:s3 作為適配器。如果所有其他方法都失敗了,Filepicker可以作為處理文件上傳的另一種方法。欲了解更多信息,請訪問 Filepicker的網站

Q&A with General Assembly Hong Kong

I was invited by General Assembly (GA) Hong Kong to talk about my experience in the Web Development Immersive (WDI) course.

1. Introduce Yourself and Describe Your Current Projects

My name is Victor, and I am a software engineer. Currently, I am working on several interesting projects that utilize JavaScript frameworks:

  1. A native iOS/Android mobile app using Ionic and the Neo4j graph database.
  2. A video chatroom using WebRTC, Node.js, and Express.js.
  3. A music visualizer using WebGL and Three.js.
  4. A LinkedIn-like network platform using Angular.js and MongoDB.
  5. A real-time voting system using Meteor.js and D3 data visualization.

Some of these are open-source projects. If you're interested in contributing or trying out the demos, please check out my GitHub.

2. Reasons for Choosing WDI at GA

Prior to enrolling in WDI at GA, I was a digital marketer responsible for social media promotions in Australia. My role sparked an interest in how technology is rapidly changing traditional media and marketing channels. Recognizing the importance of a good website as the cornerstone of digital marketing efforts, I was motivated to develop coding skills. I chose WDI at GA over night classes at a Hong Kong university because I wanted an education that was in tune with cutting-edge technologies.

3. Recapping the Student Experience

My favorite part of the WDI course was the camaraderie among students from diverse backgrounds. We all helped each other technically and emotionally. Web development is teamwork, and a website is too complex to build entirely on your own, regardless of your skill level.

4. How the Course Helped Achieve My Goals

My goal was to land a job in the industry, and GA's strong network in Hong Kong greatly assisted me. I networked extensively and participated in various events, including hackathons. Special thanks to Justin for his support during this period.

5. Top 3 Lessons from the Course

  1. Wireframing: Initially, I underestimated the importance of wireframing. With more project experience, I’ve come to realize that planning ahead saves time in the long run.
  2. User Testing: Continuous user feedback is crucial. Code should be driven by market demand and user needs, not just by what a developer thinks is cool.
  3. Learning How to Learn: The course couldn’t cover everything, so self-directed learning is crucial for ongoing development.

6. Life After GA: What's Next?

I abide by the principle of "Always Be Coding." The more you code, the better you get. Currently, I am strengthening my theoretical foundation to take on leadership roles in the IT industry.