1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ExpressでさらっとAPI

Last updated at Posted at 2019-10-04

まずは読み込み

const app = new (require('express'))()
const port = 3000
const bodyParser = require('body-parser')
const mysql = require('mysql')

dbの設定(localhost)

const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'ぱすわーど',
    database: 'でーたべーすめい'
});

dockerを使う場合は

host: 'localhost'

をDockerのコンテナに合わせて変える。

bodyPaserの設定

app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());

hogeテーブルの一覧を表示

app.get('/hoge',(req,res) => {
    connection.query('select * from hoge_table', function (error, results, fields) {
        if (error) throw error;
        res.send(results);
    });
})

hogeテーブルにデータを追加

app.post('/hoge',(req,res) => {
    const fuga = req.body.fuga;
    connection.query('INSERT INTO hoge_table SET ?', { fuga: fuga }, (err, result) => {
        if (err) throw err;
        res.send(result);
    })
})

hogeのidで返す

app.get('/hoge/:id',(req,res) => {
    const id = req.params.id
    res.send({'id': id})
})

サーバーを呼ぶ

app.listen(port, error => {
    if (error) {
        console.error(error);
    } else {
        console.info('listen: ', port);
    }
});

オワオワリ

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?