--- lang: ja-jp breaks: true --- # Node.js express を使用したWebアプリ Hello World 2021-05-10 > Node.js と Express を使用して Web API を構築する > https://docs.microsoft.com/ja-jp/learn/modules/build-web-api-nodejs-express/ ## Node.js プロジェクト作成 ```shell= $ npm init -y $ npm install express ``` ```shell= $ touch app.js ``` ## app.js ```javascript= const express = require('express'); const app = express(); const port = 3000; var content_type = { 'Content-Type': 'text/plain; charset=utf-8' }; app.get('/', (req, res) => { res.header.apply(content_type); res.send('こんにちは 世界!!'); } ); // JSON データを返す app.get("/products", (req, res) => { const products = [ { id : 1, name : "hammer", }, { id : 2, name : "screwdriver", }, { id : 3, name : "wrench", }, ]; res.json(products); } ); app.get("/products/:id", (req, res) => { res.header.apply(content_type); res.send('products id:' + req.params.id); } ); app.listen(port, () => { console.log(`Example app listening on port ${port}!`); } ); ``` ## package.json ```json= { "name": "express_sample", "version": "1.0.0", "description": "", "main": "app.js", "scripts": { "start" : "node app.js", "test": "echo \"Error: no test specified\" && exit 1", }, "repository": { "type": "git", "url": "git+https://github.com/xxxx/express_sample.git" }, "keywords": [], "author": "", "license": "ISC", "bugs": { "url": "https://github.com/xxxx/express_sample/issues" }, "homepage": "https://github.com/xxxx/express_sample#readme", "dependencies": { "express": "^4.17.1" } } ``` ## 実行 ```shell= $ npm start > express_sample@1.0.0 start /home/xxxx/work/nodejs/express_sample > node app.js Example app listening on port 3000! ``` ###### tags: `Node.js` `express` `Hello World`