Nodejs(JavaScript):
Express でWeb Serverを立ち上げ Fetch apiでアクセス

January 17, 2021 – 7:34 am

nodejsのEXPRESSでWeb Serverを立て、クライアント側にはFetch apiを配置し、サーバーからデータを取得する手続きを実装。

試行錯誤で、なんとか動くようになったのでメモしておいた。


GET Method:
 Server Side:

const express = require('express');
const app = express();

app.get('/', (req, res) => {
    res.set({'Access-Control-Allow-Origin': '*' });
    console.log(req.query)
    res.send(req.query);
});

app.listen(8080, () => {
    console.log('Example app listening on port 8080!');
});

localhost:8080を 以下で node.yamasent.com(port:80)で受ける

ServerName node.yamasnet.com
   <省略>
proxyPass / http://localhost:8080/
ProxyPassReverse / http://localhost:8080/
     <省略>

 Client Side:

<!DOCTYPE html>
<html lang="ja">
<head>
   <meta charset="UTF-8">
   <title>FETCH with Method: GET</title>
</head>
<body>
   <script>
     alert('Start!');
     const url = new URL('https://node.yamasnet.com');
     url.searchParams.append('name', 'Yamasnet');

     fetch(url)
        .then( response => response.json())
        .then( json => {
           alert(json.name);
        });
   </script>
</body>
</html>

 

POST Method:
 Server Side:

const express = require('express');
const app = express();

const bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))

app.post('/', (req, res) => {
    res.set({'Access-Control-Allow-Origin': '*' });

    const obj = JSON.parse(JSON.stringify(req.body));
    console.log(req.body.name);
    console.log(obj);
    res.send( obj );
});

app.listen(8080, () => {
    console.log('Example app listening on port 8080!');
});

 Client Side:

<!DOCTYPE html>
<html lang="ja">
<head>
   <meta charset="UTF-8">
   <title>FETCH with Method:POST</title>
</head>
<body>
   <script>
     const searchParams = new URLSearchParams;
     searchParams.append('name', 'Yamasnet');

     const param = {
           method: 'POST',
           body:   searchParams,
     };

     let url = 'https://node.yamasnet.com';

     fetch( url, param )
        .then( response => response.json())
        .then( json => {
           alert(json.name);
        });

   </script>
</body>
</html>

 
参考にしたサイト

  


Post a Comment