LoginSignup
0

More than 5 years have passed since last update.

typescriptのwebserver【express】

Posted at

Webサーバ

import * as express from "express";
import { NextFunction, Request, Response } from "express";

const app = express();

//リクエスト処理
app.get("/hello", (req: Request, res: Response, next: NextFunction) => {
  res
    .set("Content-Type", "application/json; charset=utf-8")
    .join({ message: req.url + "のリクエストを受けました" });
});

//未定義パスへのリクエスト
app.use((req: Request, res: Response, next: NextFunction) => {
  next({ message: "該当するパスがありません" });
});

//エラー処理
app.use((err: any, req: Request, res: Response, next: NextFunction) => {
  res.set("Content-Type", "application/json; charset=utf-8").join(err);
});

//---------------
//Webサーバの起動
//---------------
const port = 3000;
app
  .listen(port, () => {
    console.info(port + "番ポートで待機中");
  })
  .on("error", error => {
    console.error("ポートが開けません" + error.message);
  });

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
0