3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Nuxt.js で簡単な WebAPI を作成

Last updated at Posted at 2020-12-24

次のページを参考にしました。
Nuxtに「serverMiddleware」を設定して、API サーバ的な動きをさせてみた

実行結果
nuxt_api.png

プロジェクトの作成

npx create-nuxt-app proj01

この時点でのフォルダー構成

$ tree -L 1
.
├── README.md
├── assets
├── components
├── layouts
├── middleware
├── node_modules
├── nuxt.config.js
├── package.json
├── pages
├── plugins
├── static
├── store
└── yarn.lock

次のスクリプトでフォルダー構成を変更

go_folder.sh
mkdir client
mv assets/ client/
mv components client/
mv  layouts client/
mv middleware client/
mv pages client/
mv plugins client/
mv static client/
mv store/ client/

mkdir server
mkdir api

スクリプトを実行後のフォルダー構成

$ tree -L 1
.
├── README.md
├── api
├── client
├── node_modules
├── nuxt.config.js
├── package.json
├── server
└── yarn.lock

nuxt.config.js の変更

nuxt.config.js
export default {
serverMiddleware: ["~~/api/"],

srcDir: "./client/",
省略
api/index.js
const express = require("express");
const app = express();
const json_str = '{"en": "Hello World","ja": "こんにちは"}'

app.get("/", function(req, res) {
res.send(json_str);
});

module.exports = {
path: "/api/",
handler: app
};

サーバーの実行

yarn dev

クライアントで、
http://localhost:3000/api/
にアクセスする。

$ curl http://localhost:3000/api/ | jq .
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    45  100    45    0     0  15000      0 --:--:-- --:--:-- --:--:-- 15000
{
  "en": "Hello World",
  "ja": "こんにちは"
}
3
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?