使用fetch发送网络请求

Tutorial: React基础 Category: React Published: 2026-04-07 13:58:26 Views: 20 Likes: 0 Comments: 0

使用 fetch 发送网络请求

  1. 发送请求

    import React, { Component } from "react";
    import PubSub from "pubsub-js";
    
    export default class C1 extends Component {
      search = async () => {
        try {
          const response = await fetch(`/api1/search/users2?q=${keyWord}`);
          const data = await response.json();
          console.log(data);
          PubSub.publish("atguigu", { isLoading: false, users: data.items });
        } catch (error) {
          console.log("请求出错", error);
          PubSub.publish("atguigu", { isLoading: false, err: error.message });
        }
      };
    }
    
  2. 代理转发

    const proxy = require("http-proxy-middleware");
    
    module.exports = function (app) {
      app.use(
        proxy("/api1", {
          // 遇见/api1前缀的请求, 就会触发该代理配置
          target: "http://localhost:5000", // 请求转发给谁
          changeOrigin: true, // 控制服务器收到的请求头中Host的值
          pathRewrite: { "^/api1": "" }, // 重写请求路径(必须)
        })
      );
    };