LoginSignup
2
3

More than 3 years have passed since last update.

Expressの勉強(HTTP response)

Last updated at Posted at 2020-12-24

Expressを使ったアプリ開発

バックエンドの勉強をしようとExpressの勉強を始めました。
UdemyでExpressの勉強をしたので、復習をしながら勉強の記録を残します。

開発環境

OS : Windowos
エディター : VSCode

package.jsonの作成

sampleapp> npm init
package name: (sampleapp)
version: (1.0.0)
description:
entry point: (index.js) app.js  // エントリーポイントを変更
test command:
git repository:
keywords:
author: Mellbrother
license: (ISC)

sampleapp> npm install express --save
sampleapp>

フォルダ構成

sampleapp> tree
.
|-app.js
|-package.json

app.js

expressのサンプルコードを使用(https://www.npmjs.com/package/express)

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

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

app.listen(3000);

http://localhost:3000 にアクセスするとHello Worldと表示される。

HTTP response

上記のapp.jsのresはHTTP responseです。
resのプロパティー、メソッドのうち調べたものを下にまとめました。

res.locals

レスポンスのローカル変数を保持している。リクエストとレスポンスの一サイクルの間にview(ejsなど)で使用することができる。
リクエストのパス名や認証されたユーザーなどの情報を公開する際に使えます。


app.use(function (req, res, next) {
  res.locals.url = req.url;
  next();
});
app.get("/", function (req, res) {
  res.send(res.locals);
});

// 出力
// {"url":"/"}

res.append(field [, value])

Express v4.11.0+からサポート
指定したレスポンスヘッダーのフィールドを追加します。

valueには文字列または配列を指定可能です。
※res.append()の後にres.set()を呼ぶとヘッダーのvalueがリセットされます。


res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>'])
res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly')
res.append('Warning', '199 Miscellaneous warning')

res.cookie(name, value [,options])

cookieにnameとvalueを保存します。
valueはstringまたはjsonを指定できます。

optionsにはcookieの有効期限やsecure設定などcookieに関するオプションを設定できます。


res.cookie('name', 'tobi', { domain: '.example.com', path: '/admin', secure: true })
res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true })

res.get()

HTTPレスポンスヘッダーのフィールドを指定することによりフィールドの中身を得ることができます。


res.get('Content-Type')
// => "text/plain"

res.json([body])

json形式のレスポンスを返すときに使います。
配列, string, boolean, number, nullなどをJSON形式に変換します。


res.json(null)
res.json({ user: 'tobi' })
res.status(500).json({ error: 'message' })

res.redirect([status,] path)

与えられたURLにリダイレクトします。
statusにはHTTPステータスコードを設定できます。
指定しない場合は302番になります。


// http://localhost:3000/hogeにいるとき
res.redirect('/foo/bar') // http://localhost:3000/hoge/foo/bar
res.redirect('http://example.com') 
res.redirect(301, 'http://example.com')
res.redirect('../login') // http://localhost:3000/login

res.render(view [,locals][, callback])

viewをレンダリングし、レンダリングされたHTMLをクライアント側にレスポンスします。

localsに設定した値はテンプレートエンジンなどを用いたviewで使うことができます。

callbackを指定した場合、明示的にHTMLをレスポンスする必要があります。


// send the rendered view to the client
res.render('index')

// if a callback is specified, the rendered HTML string has to be sent explicitly
res.render('index', function (err, html) {
  res.send(html)
})

// pass a local variable to the view
res.render('user', { name: 'Tobi' }, function (err, html) {
  // ...
})

res.send([body])

HTTPレスポンスを返します。
bodyにはバッファーオブジェクト、文字列、配列などを使えます。

example
res.send(Buffer.from('whoop'))
res.send({ some: 'json' })
res.send('<p>some html</p>')
res.status(404).send('Sorry, we cannot find that!')
res.status(500).send({ error: 'something blew up' })

res.sendFile(path [, options][, fn])

Express v4.8.0からサポート
pathにあるファイルを表示します。
optionsでrootを設定することで相対パスを指定できます。

app.get("/", function (req, res) {
  res.append("Set-Cookie", "foo=bar; Path=/; HttpOnly");
  res.sendFile("index.html", {
    root: path.join(__dirname, "public"),
  });
});

renderメソッドとの違いはテンプレートエンジンを使えるかどうかです。テンプレートエンジンを使う場合にはrenderを使いましょう。htmlファイルの表示の際はどちらでも構いません。

res.sendStatus(statusCode)

HTTPステータスを設定し、ステータスコードにあった文字列を返します。

res.sendStatus(200) // equivalent to res.status(200).send('OK')
res.sendStatus(403) // equivalent to res.status(403).send('Forbidden')
res.sendStatus(404) // equivalent to res.status(404).send('Not Found')
res.sendStatus(500) // equivalent to res.status(500).send('Internal Server Error')

res.set(field [, value])

HTTPresponseヘッダーを設定します。一度に複数フィールドの設定ができます。

res.set({
  'Content-Type': 'text/plain',
  'Content-Length': '123',
  ETag: '12345'
})

res.status(code)

HTTPステータスをセットします。

res.status(403).end()
res.status(400).send('Bad Request')
res.status(404).sendFile('/absolute/path/to/404.png')

おわりに

思ったよりメソッドの数が多くて驚きました。
次回はRouterについて調べます。

2
3
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
3