React 请求Post或Get接口与Post上传文件

React 请求Post接口

1.安装 axios

npm install axios

2.页面引入axios模块

import axios from 'axios';

3.请求接口

axios.post('/getAdd', obj)
    .then(response => {
        console.log(response.data);
    })
    .catch(error => {
        console.error(error);
    });

//必须放在useEffect函数里不然防火墙视为CC
 useEffect(() => {
        axios.post('/getxxxÏ', { blok: 'demo'Ï}, {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        })
    }, [])

4.React 跨域网络请求接口 (根据需求是跨域)

在项目中的package.json文件中加上

"proxy": "http://127.0.0.1:8081",

接口请求时直接接口地址方式

axios.post('/getAdd', data)

5.请求Get接口

axios.get('http://xxxx')
  .then(response => {
    console.log(response.data);// 处理返回的数据
  })
  .catch(error => {
    console.error(error); // 处理错误
  });

6.上传文件接口post方式

// 发送文件上传请求
    const formData = new FormData();
    formData.append('files', file);
    axios.post(https + '/getUpload', formData, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    }).then(response => {// 文件上传成功处理
        console.log('File uploaded:', response.data);
        
    }).catch(error => {
        console.error(error);// 错误处理
    });

471 Views
分享你的喜爱
linwute
linwute

我要像梦一样自由,像大地一样宽容;
在艰辛放逐的路上,点亮生命的光芒;
我要像梦一样自由,像天空一样坚强;
在曲折蜿蜒的路上,体验生命的意义;

留下评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注