Skip to content

Instantly share code, notes, and snippets.

@LeeDDHH
Last active July 8, 2021 00:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LeeDDHH/87cfe8aa9fb449baf23742a68cdcd9f6 to your computer and use it in GitHub Desktop.
Save LeeDDHH/87cfe8aa9fb449baf23742a68cdcd9f6 to your computer and use it in GitHub Desktop.
expressでコーディングをする時、基本的なコードの型を思い出すためのあれこれ

基本的な express の起動

// expressモジュールをアプリケーションに追加
import express from 'express';
// ポート番号の指定
const PORT = process.env.PORT || 8080;

// expressアプリケーションをapp定数に代入
const app = express();

// jsonオブジェクトとして認識できるようになる
app.use(express.json());

// ドメインのルートにGet経路を設定する
app.get('/', (req, res) => res.send('Express + TypeScript Server is work!'));

// 指定したポートを監視するようにアプリケーションを設定する
app.listen(PORT, () => {
  console.log(`[server]: Server is running at https://localhost:${PORT}`);
});

expressmongodbmongoose でつなげる

前提

  • mongodb は起動している
  • mongodb のポートはデフォルトのポート番号
  • DBはすでに生成されている
import express from 'express';
import mongoose from 'mongoose';

const DB_URL = 'mongodb://127.0.0.1:27017/';
const DB_NAME = 'comic_impressions_exchange_db';
const PORT = process.env.PORT || 8080;

const dbOption = {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  useFindAndModify: false,
  useCreateIndex: true
};

mongoose.connect(`${DB_URL}${DB_NAME}`, dbOption);

mongoose.Promise = global.Promise

const db = mongoose.connection;

db.once('open', () => {
  console.log('MongoDB open Success with Mongoose');
});

const app = express();

app.use(express.urlencoded({ extended: false }));
app.use(express.json());

app.set('port', PORT);

app.listen(app.get('port'),() => {
  console.log(`[server]: Server is running at https://localhost:${app.get('port')}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment