我正在尝试从Vue.js和console.log中的API获取数据,但是出现了CORS问题,最具体的是:
from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我了解到我需要创建一个vue.config.js
文件,但没有做任何更改,我也尝试仅使用fetch api,也许我在Vue中以错误的方式调用了http,如何获取我的数据并解决此错误?
这是我的组成部分:
<template>
<div class="container">
</div>
</template>
<script>
import axios from "axios";
export default {
name: "HelloWorld",
methods: {},
mounted() {
axios
.get(
"https://base-url"
)
.then(response => console.log(response));
}
};
</script>
和我的vue.config.js
:
module.exports = {
devServer: {
proxy: 'base-url',
}
}
答案 0 :(得分:0)
我认为您可能需要在要调用的端点中设置中间件,如下所示:
// ACCEPTING CROSS SITE REQUESTS
api.use(cors());
api.use((req, res, next)=>{
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
请尝试将其添加到您要从中调用的端点API,以便可以授权新的调用。
答案 1 :(得分:0)
您应该有 “访问控制允许来源:” 标头
,因此请确保您的[api基本URL]返回此标头以使您的浏览器 允许您的请求通过而不会受到(作为保护的方式)
的更多信息PHP中的示例:
<?php
header('Access-Control-Allow-Origin: *') // to allow all sites
... the rest of the code
答案 2 :(得分:0)
答案 3 :(得分:-1)
我发现自己在做错什么,设置代理后,我不得不将get请求更改为
mounted() {
axios
.get(
"http://localhost:8080/https://base-url"
)
.then(response => console.log(response));
解决了这个问题。