6
7

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 5 years have passed since last update.

Nuxt.js & Express プロジェクト作成

Last updated at Posted at 2018-07-24

Nuxt.jsプロジェクトでRestAPIも実装する

Nuxt.jsプロジェクト作成

ここではexpressをインストールしない

> npx create-nuxt-app nuxt-sample
> Generating Nuxt.js project in C:\nuxt-sample
image.png

Express をプロジェクトへ追加

npm install --save express
npm install --save body-parser

nuxt.config.jsの変更

//add for API
const bodyParser = require('body-parser')

module.exports = {
  mode: 'universal',
  /**
  * add for API
  */
  serverMiddleware:[
  bodyParser.json(),
  '~/api'
  ],

APIの作成

/api/index.js

node.js
const express = require("express");
const router = express.Router();

const app = express()
router.use((req, res, next) => {
  Object.setPrototypeOf(req, app.request)
  Object.setPrototypeOf(res, app.response)
  req.res = res
  res.req = req
  next()
})

router.get("/test/:id", (req, res) => {
   console.log("--test get");
   console.log("--id " ,req.params.id)
   res.status(200).json({message:`test_id = ${req.params.id}`});
});

module.exports = {
  path: '/api',
  handler: router
}

動作確認

>npm run dev
image.png

テスト・開発用Expressを用意する

/api/apptest.js

> npm install cors --save

node.js
const {path,handler} = require('./index')
const bodyParser = require("body-parser");
const express = require("express");
const cors = require("cors")
const app = express()

var corsOptions = {exposedHeaders: 'x-auth'}
app.use(cors(corsOptions));

app.use(bodyParser.json());
app.use(path,handler);
port="3000"
app.listen(port,()=>{
   console.log(`Started up apptest port:${port}`);
});
//for test {path,app}
module.exports = { path,app };

動作確認

> node api/apptest
image.png

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?