在 Express 中處理 HTTP 標頭

學習如何使用 Express 存取和更改 HTTP 標頭 從請求中存取 HTTP 標頭值 您可以使用 Request.headers 屬性存取所有的 HTTP 標頭: app.get('/', (req, res) => { console.log(req.headers) }) 使用 Request.header() 方法來存取個別請求標頭的值: app.get('/', (req, res) => { req.header('User-Agent') }) 更改回應的任何 HTTP 標頭值 您可以使用 Response.set() 來更改任何 HTTP 標頭的值: res.set('Content-Type', 'text/html') 然而,Content-Type 標頭有一個捷徑: res.type('.html') // => 'text/html' res.type('html') // => 'text/html' res.type('json') // => 'application/json' res.type('application/json') // => 'application/json' res.type('png') // => image/png: