在使用 Axios 发送跨域请求时,经常会遇到 'Access-Control-Allow-Origin' 缺失 的报错,例如:

Access to XMLHttpRequest at 'http://localhost:8888/task/findAllTask' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

该错误表明浏览器因为安全策略限制,阻止了来自不同域的请求访问。为了解决这个问题,可以从以下两个方面着手:

1. 后端服务器配置

在后端服务器的响应中添加 Access-Control-Allow-Origin 头部信息,允许跨域访问。

例如,使用 Node.js Express 框架,可以在路由处理函数中添加以下代码:

app.get('/task/findAllTask', (req, res) => {
  // 处理请求逻辑...
  res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080'); // 设置允许跨域访问的源地址
  res.send(data); // 发送响应数据
});

2. 前端代码修改

在前端发送请求时,加入 mode: 'cors',告诉浏览器该请求是跨域请求。

例如,使用 Axios 库,可以在发送请求时添加 mode: 'cors' 参数:

axios.post('http://localhost:8888/task/findAllTask', { token }, { mode: 'cors' })
  .then(response => {
    this.taskList = response.data;
    this.nextId = response.data.length;
  })
  .catch(error => {
    console.log(error);
  });

注意: 为了安全考虑,在配置 Access-Control-Allow-Origin 时,应根据实际需求设置允许跨域访问的源地址,避免出现安全漏洞。


原文地址: https://www.cveoy.top/t/topic/mmx6 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录