[英]Vue.js GET request to API gets blocked by CORS
I am trying to fetch data from an API in Vue.js and console.log the response but I get a CORS problem, most specifically: 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,也许我正在让 http 在 Vue 中调用错误的方式,我怎样才能获取我的数据并解决这个错误?
这是我的组件:
<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',
}
}
我认为您可能需要在您调用的端点中设置一个中间件,如下所示:
// 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 以便可以授权新呼叫。
你应该有 'Access-Control-Allow-Origin: ' Header
所以请确保您的 [api base url] 返回此 header 以使您的浏览器允许您对 go 的请求通过而不被(作为保护方式)
有关访问控制允许来源的更多信息
PHP 中的示例:
<?php
header('Access-Control-Allow-Origin: *') // to allow all sites
... the rest of the code
在最新版本的 vuejs 中,例如,如果远程 api 位于 http://localhost:9002/tasks,则使用服务器配置。
// vite.config.js
import { defineConfig } from 'vite'
export default defineConfig({
server: {
proxy: {
'/tasks': 'http://localhost:9002'
}
}
})
我发现我做错了什么,在设置代理后,我不得不将我的获取请求更改为
mounted() {
axios
.get(
"http://localhost:8080/https://base-url"
)
.then(response => console.log(response));
这解决了这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.