2
1

同じexpressのプロセスでドメインごとに違うページを表示する

Last updated at Posted at 2024-03-13

はじめに

  • expressでサーバーを起動
  • example1.jpとexample2.jpで別のサイトを表示したい
  • おなじNodeJSのプロセスで複数ドメインを扱う方法で悩んだ

解決策

Routerというもので分岐ができるらしい
ドメインでも分岐できないか?
→使い方が正しいかわからないけど下のコードで解決!

コード

index.js
const express = require("express");
const app = express();

// ドメインごとに読み込む
const domain1 = require("./example1.js");
const domain2 = require("./example2.js");

app.use( (req, res, next) => {
  // アドレスのホスト名(ドメイン)
  var host = req.hostname;
  
  if( host == "example1.jp" ) {
    // routerに飛ばす
    domain1(req, res, next);
  } else if( host == "example2.jp") {
    // 別のrouterに飛ばす
    domain2(req, res, next);
  } else {
    // どれにも対応しない場合
    next();
  }
});

// 404 error
app.use(function(req, res, next){
  res.status(404);
  res.end("404 error");
});

// 3000番ポートで開く
app.listen(3000, function () {
  console.log(`listening on port 3000!`);
});
example1.js
const express = require("express");

// Routerをつくる
const example1 = express.Router();

example1.get("/", (req, res) => {
  res.send("example1.jp!");
});
example1.get("/hello", (req, res) => {
  res.send("Hello, world! from example1.jp");
});
example2.js(1とほぼ同じ)
example2.js
const express = require("express");

// Routerをつくる
const example2 = express.Router();

example2.get("/", (req, res) => {
  res.send("example2.jp!");
});

完成

サンプルをそのままうつすと下のように返ってくるようになります

アドレス サイトの表示
example1.jp:3000/ example1.jp!
example1.jp:3000/hello Hello, world! from example1.jp
example2.jp:3000/ example2.jp!
example2.jp:3000/hello 404 error
2
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
2
1