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));
});
posted @ 2021-07-14 15:10  STRIVE-PHY  阅读(63)  评论(0编辑  收藏  举报