山东大学小组项目实训前端二

前端访问后端接口:

使用原生JavaScript的fetch API

fetch是一个现代的、基于Promise的HTTP客户端,用于浏览器和Node.js中。

fetch('https://api.example.com/data', {  
  method: 'GET', // 或者 'POST', 'PUT', 'DELETE' 等  
  headers: {  
    'Content-Type': 'application/json', 
  },  
  body: JSON.stringify(data), 
})  
.then(response => response.json())  
.then(data => console.log(data))  
.catch((error) => {  
  console.error('Error:', error);  
});

在vue中使用是这样的:

<template>  
  <!-- ... 模板内容 ... -->  
</template>  
  
<script>  
export default {  
  data() {  
    return {  
      data: null, // 初始化数据为空  
    };  
  },  
  methods: {  
    fetchData() {  
      fetch('https://api.example.com/data')  
        .then(response => {  
          if (!response.ok) {  
            throw new Error('Failed to fetch data');  
          }  
          return response.json(); // 解析 JSON 响应  
        })  
        .then(data => {  
          this.data = data; // 将解析后的数据保存到组件的 data 中  
        })  
        .catch(error => {  
          console.error('Error fetching data:', error); // 处理错误  
        });  
    },  
  },  
};  
</script>
使用axios库

axios是一个基于Promise的HTTP客户端,可以在浏览器和node.js中使用。它提供了许多有用的特性,如拦截请求和响应、转换请求和响应数据等。

首先,需要安装axios(如果你正在使用npm或yarn):

npm install axios  
# 或者  
yarn add axios

然后在你的代码中使用它:

import axios from 'axios';  
  
axios.get('https://api.example.com/data')  
  .then(function (response) {  
    console.log(response.data);  
  })  
  .catch(function (error) {  
    console.log(error);  
  });

而在vue中使用是这样的:

<template>  
  <div>  
    <button @click="fetchData">获取数据</button>  
    <div v-if="data">  
      <!-- 显示数据 -->  
      <p>{{ data.message }}</p>  
    </div>  
  </div>  
</template>  
  
<script>  
import axios from 'axios';  
  
export default {  
  data() {  
    return {  
      data: null, // 初始化数据为空  
    };  
  },  
  methods: {  
    fetchData() {  
      axios.get('https://api.example.com/data')  
        .then(response => {  
          this.data = response.data; // 将响应数据保存到组件的 data 中  
        })  
        .catch(error => {  
          console.error(error); // 处理错误  
        });  
    },  
  },  
};  
</script>

注意事项:

跨域问题:如果你的前端和后端不在同一个域或端口上运行,你将面临跨域资源共享(CORS)问题。你需要确保后端服务器已配置适当的 CORS 策略来允许前端进行跨域请求。
错误处理:始终处理 HTTP 请求中的错误。在上面的示例中,我们使用了 catch 块来捕获并处理错误。
安全性:确保你的 API 请求是安全的。使用 HTTPS 来加密你的请求,并考虑使用身份验证和授权机制(如 OAuth、JWT 等)。
请求和响应拦截:如果你使用的是 axios,你可以使用请求和响应拦截器来在请求发送到服务器之前或响应返回给前端之前进行额外的处理。
状态管理:如果你的 Vue 应用有多个组件需要共享后端数据,考虑使用 Vuex 或其他状态管理库来管理这些数据。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值