【发布时间】:2018-02-01 14:57:16
【问题描述】:
我正在开发一个 vuejs 组件,该组件使用 axios 向 Yahoo 天气 API 发出 ajax GET 请求。我收到 CORS 错误,因为预检检查未通过访问控制检查。
但是,我可以毫无问题地使用 jqueries ajax 方法向同一个端点发出请求,并且从服务返回预期的数据。有谁知道为什么会这样?
这是我的 vue 组件中的代码:
<template>
<div class="tile" id="time-weather">
<div class="date" v-text='this.date'></div>
<div class="time" v-text='this.time'></div>
<div class="temperature" v-text="this.temp"></div>
</div>
</template>
<script>
import moment from 'moment';
export default {
created() {
this.refreshTime();
setInterval(this.refreshTime, 1000);
this.fetchWeather();
},
data() {
return {
date: '',
time: '',
temp: ''
}
},
methods: {
refreshTime() {
this.date = moment().format('ddd DD/MM');
this.time = moment().format('HH:mm:ss');
},
fetchWeather() {
const endpoint = "https://query.yahooapis.com/v1/public/yql?q=select item.condition from weather.forecast where woeid in (select woeid from geo.places(1) where text='Sunderland') and u='c'&format=json";
const yapi = axios.create({
url: endpoint,
method: 'get',
withCredentials: false
});
const response = yapi.request();
console.log(response);
}
}
}
</script>
我在控制台中收到的确切错误消息是:
XMLHttpRequest 无法加载 https://query.yahooapis.com/v1/public/yql?q=select%20item.condition%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text=%27Sunderland%27)%20and%20u=%27c%27&format=json。 对预检请求的响应未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。因此不允许使用原点“http://dashboard.dev” 访问。
正如我所提到的,如果我使用 jQuery.ajax(); 向同一个端点发出请求,则请求将毫无问题地发送。
我可能缺少一些明显的东西,但我似乎无法解决这个问题。
任何帮助将不胜感激。
干杯!
【问题讨论】:
-
你确定吗?给定端点返回 404。刚刚用 cURL 检查了它。
-
@jimmyweb 编辑了指向 https 的链接,我的错。仍然得到相同的结果。
-
查看刚刚添加的答案。您可以进入浏览器 devtools 中的 Network 窗格并重新加载文档,然后在那里检查浏览器发送的 preflight OPTIONS 请求。您应该检查请求标头 - 特别是浏览器发送的
Access-Control-Request-Headers请求标头。这将包含 axios 请求尝试添加到请求中的任何自定义请求标头的名称(这会导致预检失败)。也许使用stackoverflow.com/posts/45849535/edit 来编辑/更新问题并粘贴到这些响应标题中。
标签: jquery ajax cors vuejs2 axios