LoginSignup
10
10

More than 5 years have passed since last update.

Nuxt 2.xでexpressを使ってhello worldするまでの道のり【備忘録】

Posted at

expressについては今まで扱ったことがなく、Nuxtとどのように連動するのか、実際のところまだしっかり理解できていません。とりあえずここでは、nuxtプロジェクトでexpressを使うまでの初期設定までをリサーチしたので、備忘録として記録。

現在のnuxtのバージョンは以下のコマンドから分かるのかな?

./node_modules/nuxt/bin/nuxt.js -v

@nuxt/cli v2.4.2

バージョンはv2.4.2のようです。

hello worldまでの道のり

  • nuxtでプロジェクトを作成
npx create-nuxt-app <project-name>
  • プロジェクトルートにapiフォルダーを用意
  • apiフォルダにindex.jsを追加して以下の内容を記入
/api/index.js
const app = require('express')()
module.exports = { path: '/api', handler: app }

app.get('/hello', (req, res) => {
    console.log('hello nuxt in text')
    res.send('world')
})

注意点

Notice, there is no /api prefix in the app.get(), above. This is because in module.exports we already specified the "global" prefix as /api for this whole express router instance.

つまり、app.getのパスはグローバルで登録している/api以降のパスを登録する。

  • nuxt.config.jsにserverMiddlewareを追加
    • middlewareではないことに注意!
nuxt.config.js
serverMiddleware: ['~/api/index.js'],

nuxt.config.jsはdeaultではwatchされていないので、ホッとリロードされない。起動していたら、再起動する必要がある。

  • localhost:3000/api/helloにアクセスして、画面にworldと表示されれば成功
    • 当たり前かもしれないが、console.log('hello nuxt in text')の出力はwebのコンソールではなく、端末のコンソール上に表示される。

これで、vue側からjsonをなどを取得する際にlocalhost:3000/api/helloなどでアクセスすると、express経由で処理を行えると思う。

10
10
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
10
10