よくあるリダイレクトチェックツールを作ってみた
github.com
axiosでリダイレクト一覧を取得できる機能のプルリクが出ているのでそれを利用させてもらって、serverlessで下記のような雑なコードをバックエンドとして書いた。
'use strict' const axios = require('axios') const ACCESS_CONTROL_ALLOW_ORIGIN = process.env.ACCESS_CONTROL_ALLOW_ORIGIN module.exports.trace = async (event, context) => { const { headers, body } = event const parsedBody = JSON.parse(body) try { const { redirects } = await axios.get(parsedBody.url, { trackRedirects: true }) return { statusCode: 200, headers: { "Access-Control-Allow-Origin": ACCESS_CONTROL_ALLOW_ORIGIN }, body: JSON.stringify({ redirects }) } } catch (e) { if (!e.response) return { statusCode: 400, headers: { "Access-Control-Allow-Origin": ACCESS_CONTROL_ALLOW_ORIGIN }, body: JSON.stringify({ error: 'invalid url' }) } return { statusCode: 200, headers: { "Access-Control-Allow-Origin": ACCESS_CONTROL_ALLOW_ORIGIN }, body: JSON.stringify({ redirects: e.response.redirects }) } } }
serverless.ymlは下記のような感じ
service: redirect-checker-backend provider: name: aws runtime: nodejs8.10 region: ap-northeast-1 stage: ${opt:stage, self:custom.defaultStage} environment: ACCESS_CONTROL_ALLOW_ORIGIN: ${self:custom.accessControlAllowOrigin.${self:provider.stage}} custom: defaultStage: dev accessControlAllowOrigin: dev: http://localhost:5000 prod: https://example.com plugins: - serverless-offline functions: trace: handler: handler.trace memorySize: 128 events: - http: path: trace method: post cors: true
フロントが別ドメインのため、cors: true
をserverless.ymlに設定して、ヘッダーにACCESS_CONTROL_ALLOW_ORIGINを付与している。