vue.js - 使用 Axios 和 VueX 的 Vue 应用程序在本地主机上被 CORS 阻止 :3000?

标签 vue.js axios localhost vuex connection-refused

自从切换到从 VueX 存储 (db.json) 文件而不是在线版本的 json 文件加载数据以来,我在预览应用程序时遇到了问题。

在 Chrome 上我收到错误:

GET http://localhost:3000/events net::ERR_CONNECTION_REFUSED

在 Firefox 上我收到错误:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3000/events. (Reason: CORS request did not succeed)

我尝试了一些不同的操作,例如添加访问控制 header 、将凭据设置为 true,并在 127.0.0.1 地址(而不是 localhost)上尝试此操作,但仍然没有任何运气。

执行 Axios 调用的我的 EventService.js 文件是:

import axios from 'axios'

const apiClient = axios.create({
  baseURL: 'http://localhost:3000',
  
  withCredentials: false,
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'GET, PUT, POST',
    'Access-Control-Allow-Headers': 'Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With'
  }
})

export default {
  getEvents() {
    return apiClient.get('/events')
  },
  getEvent(id) {
    return apiClient.get('/events/' + id)
  },
  postEvent(event) { 
    return apiClient.post('/events', event)
  }
}

当无法建立连接时,它只是默认返回到我的 NetworkError 组件回退。

最佳答案

在这里发布答案以避免其他人头痛。

看起来我需要在项目的根目录中设置一个单独的 vue.config.js 文件,其中包含:

module.exports = {
    devServer: {
        proxy: 'http://localhost:3000'
    }
}

然后,我必须更改通过 EventService.js 文件(链接到 VueX 存储和 db.json 的文件)执行的调用,以从 baseURL 中删除 localhost:3000,如下所示:

import axios from 'axios'

const apiClient = axios.create({
 // baseURL: 'http://localhost:3000', // Not required due to proxy
  
  withCredentials: false,
  headers: {
    Accept: 'application/json'
  }
})

export default {
  getEvents() {
    return apiClient.get('/events')
  },
  getEvent(id) {
    return apiClient.get('/events/' + id)
  },
  postEvent(event) { 
    return apiClient.post('/events', event)
  }
}

关于vue.js - 使用 Axios 和 VueX 的 Vue 应用程序在本地主机上被 CORS 阻止 :3000?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69613661/

相关文章:

ruby - 无法预览 Octopress 生成的网站

macos - MAC、MAMP、127.0.0.1 连接被拒绝,本地主机正常

javascript - Vue路由器在路线上保存滚动位置并在导航时返回该位置?

javascript - Firebase 云消息传递前台通知在 Vue 中不起作用

typescript - VueJS + TypeScript 装饰器问题

node.js - 查询 WordPress WP-API 中的大量帖子(使用 Promise!)

javascript - Vue,获取返回空数组

javascript - 设置从 axios 到状态的响应

javascript - axios 条件参数

php - localhost:8000 继续加载,没有任何错误或正确输出