Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

vue cors

作者:Alexandr嫁衣°   发布日期:2025-06-06   浏览:46

// Vue 项目中处理 CORS 的示例代码

// 在 main.js 中配置代理,解决开发环境下的 CORS 问题
const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: 'http://example.com', // 目标 API 服务器地址
        changeOrigin: true,           // 更改请求的origin
        pathRewrite: {
          '^/api': ''                 // 重写路径,去掉 /api 前缀
        }
      }
    }
  }
};

// 在组件中使用 axios 发送请求
import axios from 'axios';

export default {
  methods: {
    fetchData() {
      axios.get('/api/data') // 请求会被代理到 http://example.com/data
        .then(response => {
          console.log(response.data);
        })
        .catch(error => {
          console.error(error);
        });
    }
  }
};

解释说明:

  1. 代理配置:通过在 main.js 中配置 devServer.proxy,可以在开发环境中将 /api 开头的请求代理到目标服务器(如 http://example.com),从而避免浏览器中的跨域问题。
  2. Axios 请求:在 Vue 组件中使用 axios 发送请求时,直接请求 /api/data,实际请求会被代理到 http://example.com/data。这样可以避免直接请求外部域名导致的 CORS 问题。

上一篇:vue数组对象去重

下一篇:vue本地存储和获取数据

大家都在看

vue.config.js configu

node.js vue

vue查看版本

vue等待几秒

vue3 setup computed

vue screenfull

vue json.stringify

vue 遍历list

typescript vue

vue 复选框

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站