【问题标题】:Returning json data from url with Vue.js使用 Vue.js 从 url 返回 json 数据
【发布时间】:2020-08-24 04:33:27
【问题描述】:

我正在开发一个简单的应用程序,它从某个 url 的 json 资源返回一个值。 虽然我已经创建了一个vue.config.js 文件来避免 CORS 问题,但仍在执行消息:

CORS 策略已阻止从源“http://localhost:8080”获取“https://api.darksky.net/forecast/xxx/37.8267,-122.4233”的访问权限: 请求的资源上不存在“Access-Control-Allow-Origin”标头。 如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

我错过了什么?非常感谢!

位置.vue

<template>
  <div>
    <h1>{{ forecast.timezone }}</h1>
  </div>
</template>

<script>
export default {
  name: 'Location',
  props: {
    forecast: Array
  }
}
</script>

App.vue

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png">
    <location v-bind:forecast="forecast" />
  </div>
</template>

<script>
import Location from './components/Location.vue'

export default {
  name: 'App',
  components: {
    Location
  },
  data() {
    return {
      forecast: []
    }
  },
  mounted() {
    this.getTimeZone()
  },
  methods: {
    async getTimeZone() {
      try {
        const response = await fetch('https://api.darksky.net/forecast/xxx/37.8267,-122.4233')
        const data = await response.json()
        this.forecast = data
      } catch (error) {
        console.error(error)
      }
    }
  }
}
</script>

vue.config.js

module.exports = {
  devServer: {
    proxy: 'https://api.darksky.net/forecast/xxx/'    
  }
}

【问题讨论】:

  • 我看不出 vue.config.js 如何解决你的 CORS 问题。服务器需要响应 OPTION 调用并允许进一步的 HTTP 调用。

标签: vue.js


【解决方案1】:

您需要为外部 API 设置 CORS 策略。它与vue.js 无关。

或者,如果外部 API 是 3rd-party API 并且您无法更改 CORS 政策,那么您可以在服务器端代码中使用外部 API,并在服务器端代码中创建您自己的 API,该 API 将返回您从外部 API 获得的任何价值。

【讨论】:

    【解决方案2】:

    来自 Vue Cli 文档:

    警告

    当 devServer.proxy 设置为字符串时,仅代理 XHR 请求。如果您想测试 API URL,请不要在浏览器中打开它,而是使用 Postman 之类的 API 工具。

    因此,设置 devServer.proxy 属性并不能解决问题,因为 api 请求不会被代理。正如断路器建议的那样,对于永久解决方案,您必须在 api 服务器上允许 CORS 请求。

    【讨论】:

      猜你喜欢
      • 2021-10-17
      • 1970-01-01
      • 2016-08-15
      • 1970-01-01
      • 2021-09-19
      • 1970-01-01
      • 2019-06-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多