vue 已被CORS策略阻止:请求的资源上不存在“Access Control Allow Origin”标头。
时间: 2024-03-15 07:47:50
浏览: 285
在 Vue 中,通常会使用 Axios 或者 Fetch 发起 HTTP 请求。如果你遇到了 CORS 跨域问题,可以在请求中添加 `withCredentials: true` 选项来解决该问题。
例如,使用 Axios 发起带有 `withCredentials: true` 选项的 GET 请求:
```javascript
axios.get('https://example.com/api/data', {
withCredentials: true
同时,在服务端也需要设置 `Access-Control-Allow-Origin` 标头为允许跨域的域名,可以设置为 `*` 表示允许来自任意域名的跨域请求。
如果你在开发环境中使用的是 Vue CLI 提供的 devServer,可以在 `vue.config.js` 文件中添加以下配置来解决跨域问题:
```javascript
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'https://example.com',
changeOrigin: true,
withCredentials: true
这样,当你在客户端发起 `/api` 开头的请求时,Vue CLI 会自动将请求代理到 `https://example.com`,并在请求中添加 `withCredentials: true` 选项。同时,服务端需要设置 `Access-Control-Allow-Origin: *` 标头来允许跨域请求。
阅读全文
相关推荐

















