發表文章

目前顯示的是 2016的文章

Amazon S3 正確處理 HTML5 History 路由問題

圖片
如果你是使用 Angular、React 或是 Vue 來開發 SPA(單頁面應用),並且放在 Amazon S3 Static Website Hosting 上的話,那麼你會碰到 URL routing 的問題。 一般 react-router 或 vue-router 都預設使用 hash 的方式來處理 SPA 的路由: http://domain.com/#!/paths 如果你不喜歡 #!/ 的顯示方式,可以使用 HTML5 的 History API ,這樣就能像一般網站那樣顯示 URL: http://domain.com/paths 但是使用 HTML5 History API 時,通常必須搭配 server 端正確的 路由配置 才能防止出現 404 Not Found 的情形。 遺憾的是,在 Amazon S3 Static Website Hosting 上,你無法更動 Apache 或 Nginx 的配置,所以需要靠其它方式來解決問題。 使用 S3 的 Redirection Rules 使用 CloudFront 的 Custom Error Response 使用 S3 的 Redirection Rules Amazon S3 Static Website Hosting 提供了 Edit Redirection Rules 的選項,我們可以輕鬆使用這段程式碼將所有 domain.com/#!/paths 所產生的 404,全部重新導向至根路徑: <RoutingRules> <RoutingRule> <Condition> <HttpErrorCodeReturnedEquals>404</HttpErrorCodeReturnedEquals> </Condition> <Redirect> <HostName>你的網域(例:domain.com)</HostName> <ReplaceKeyPrefixWith>#!/</ReplaceKeyPrefixWith> </Redirec

如何正確處理 AWS API Gateway 的 Lambda Error Status

圖片
翻譯自原文 Error handling in AWS API Gateway with Lambda 這篇文章會介紹如何設置 AWS API Gateway 正確處理 Lambda 返回的 HTTP 錯誤狀態碼。 更新:2016.03.12 claudia 可以自動化解決這個問題,詳細可以參考 這篇 文章。 本文假設讀者已經知道如何利用 AWS API Gateway 和 Lambda 建立 REST API,詳細可參考 Create API Gateway API for Lambda Functions 。 假設你的 Lambda function 錯誤處理如下: console.log('I am a AWS Lambda function'); exports.handler = function(event, context) { // 一般使用 context.fail 來返回 Lambda function 錯誤 context.fail(JSON.stringify({status:'fail', reason:'some reason', foo:'bar'})); }; 但是 API Gateway 返回的結果會是 HTTP 200 : HTTP/1.1 200 OK ... { "errorMessage": "{\"status\":\"fail\",\"reason\":\"some reason\",\"foo\":\"bar\"}" } 我們希望的結果是: HTTP Status 400 Bad request 只顯示 errorMessage 的 JSON 值 1. 新增 HTTP Status 400 Method Response 前往 API Gateway Console 進入 Method Execution 進入 Method Response 點選 Add Response 輸入 HTTP Status 400 點選