LoginSignup
3
1

More than 3 years have passed since last update.

オープンソース LWC でカスタム Express サーバーの設定方法

Last updated at Posted at 2019-07-26

この記事では、オープンソース LWC のカスタム Express サーバーの設定方法と、 バックエンドサーバーとすべく API の追加方法及び呼び出し方法について書いてみました。

LWC のカスタム Express サーバー

オープンソース LWC は UI フレームワークのため、所謂フロントエンドサーバーを自前で用意する必要があります。
lwc-create-app でプロジェクトを作成すると、簡単にホストとなる Express サーバーを開始できるため、すぐに開発を始められます。
また、この Express サーバーを拡張するためのオプションも容易されており、簡易的なバックエンドサーバーとして実装する事も可能です。

プロジェクトを作成する

まずは lwc-create-app を使って、プロジェクトを作成します。
基本的にはプロンプトに従ってデフォルトのまま進めていますが、Use custom Express server configurationy と答えると、Express サーバーを拡張できるようになります。

$ npx lwc-create-app custom-express-server

? Package name for npm custom-express-server
? Description 
? Author 
? Version 0.0.0
? License MIT
? Who is the GitHub owner of the repository (https://github.com/OWNER/repo) 
? What is the GitHub name of the repository (https://github.com/owner/REPO) custom-express-server
? Select a package manager npm
? Register web component No
? Use custom Express server configuration Yes

Express サーバーに API を追加する

src/server/index.js を開き、app に対して機能や設定を追加していきます。
今回は、顧客 ID を指定して顧客情報を返す API を作成しました。

src/server/index.js
module.exports = app => {
    const contacts = {
        '1': {
            name: '名取 光彦',
            birthday: '1978/3/7',
            email: 'LYdvR@sample.jp'
        },
        '2': {
            name: '増子 達志',
            birthday: '2000/5/30',
            email: 'fq43mm@test.co.jp'
        }
    };
    app.get('/contact/:id', function (req, res) {
        res.json(contacts[req.params.id]);
    });
};

LWC コンポーネントから API を呼び出す

ルートコンポーネントとなっている src/client/modules/my/app/app.js に、以下の様に追記します。
JavaScript の Fetch API を使って、作成した API を呼び出し結果をコンソールログに吐き出します。

src/client/modules/my/app/app.js
import { LightningElement } from 'lwc';
export default class App extends LightningElement {
    connectedCallback() {
        fetch('/contact/1')
            .then(response => response.json())
            .then(json => console.log(json));
    }
}

ブラウザで確認する

クライアント側とサーバー側のコードを変更出来たので、以下のコマンドでビルドしてサーバーを立ち上げます。

$ cd custom-express-server
$ npm run build
$ npm run serve
> 🌎  Local server listening: http://0.0.0.0:3002

ブラウザで http://0.0.0.0:3002 にアクセスします。
コンソールログを確認すると、カスタム Express サーバーに追加した API が返す値が表示されています。

watch モードで確認する

LWC コンポーネントファイルへの変更を即座にブラウザにも反映してくれる watch モードでは webpack の devServer が立ち上がるので、上で作成した API にはアクセスできません。
そのため、別途 API サーバーとして立ち上げる必要があるのですが 2つのサーバーに別々のポート番号が割り当てられるため、そのままでは CORS ポリシーに違反してしまいます。
そういった場合には、以下の様に lwc-services-config.jsdevServer にプロキシ設定を追記しておきます。

lwc-services-config.js
module.exports = {
    resources: [{ from: 'src/client/resources', to: 'dist/resources' }],
    sourceDir: './src/client',
    moduleDir: './src/client/modules',
    server: {
        customConfig: './src/server/index.js'
    },
    devServer: {
        proxy: { '/': 'http://localhost:3002'},
    },
};

そして、再度ビルドし両方のサーバーを立ち上げ、watch している http://0.0.0.0:3001 をブラウザで開きます。

Terminal-1
$ npm run build
$ npm run serve
> 🌎  Local server listening: http://0.0.0.0:3002
Terminal-2
$ npm run watch
> 📦  Starting build process.
> 🌎  Local server listening: http://0.0.0.0:3001
3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1