ajax——使用fetch函数发送请求

1.代码

1.1前端代码

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>AJAX POST 请求</title>
    <style>
      #result {
    
    
        width: 200px;
        height: 100px;
        border: solid 1px #90b;
      }
    </style>
    <script crossorigin="anonymous"></script>
  </head>
  <body>
    <button>发送请求</button>
    <div id="result"></div>
  </body>
  <script>
    btn = document.getElementsByTagName("button")[0]
    console.log(btn)
    btn.onclick = function () {
    
    
      console.log("点击");
      fetch("http://127.0.0.1:8000/server", {
    
    
        method: "POSt",
        headers: {
    
     name: 'lixv' },
        body: "a=1&b=2",
      }).then( response =>{
    
    
        return response.json();
      }).then(response =>{
    
    
        console.log(response)
      });
    };
  </script>
</html>

1.2服务端代码

const express = require("express");
const app = express();
const cors = require("cors");
app.use(cors());

app.all("/server", (request, response) => {
    
    
  response.setHeader("Access-Control-Allow-Origin", "*");
  const data = {
    
    
    name: "lixv000",
  };
  let str = JSON.stringify(data);

  response.send(str);
});

app.listen(8000, () => {
    
    
  console.log("服务已经启动,8000端口监听中……");
});

2.代码讲解

无须讲解

3.运行结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_45895576/article/details/114267018