1. 程式人生 > 其它 >fetch函式傳送Ajax請求

fetch函式傳送Ajax請求

fetch.html

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>fetch 傳送AJAX請求</title>
</head>

<body>
  <!-- 210323 -->
  <button>AJAX請求</button>
  <script>
    const btn = document.querySelector('button');
    btn.onclick = function () {
      //第一個引數url,第二個引數:request物件  可以設定行頭體
      fetch('http://127.0.0.1:8000/fetch-server?vip=10', {
        method: 'POST',
        headers: {
          name: 'phy'
        },
        body: 'username=phy&password=123'
      }).then(response => {
        //console.log(response);
        return response.json();
        // return response.text();
      }).then(response => {
        console.log(response);
      })
    }
  </script>
</body>

</html>

server.js

//fetch服務
app.all('/fetch-server', (request, response) => {
  //設定響應頭 設定允許跨域
  response.setHeader('Access-Control-Allow-Origin', '*');
  response.setHeader('Access-Control-Allow-Headers', '*')
  //設定響應體
  // response.send('Hello jQuery Ajax');
  const data = {
    name: 'phy'
  };
  response.send(JSON.stringify(data));
});