[英]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.
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.
I read that I need to create a vue.config.js
file, I did but nothing changed, I also tried just using the fetch api, maybe I am making http calls the wrong way in Vue, how can I get my data and resolve this error?我读到我需要创建一个vue.config.js
文件,我做了但没有任何改变,我也尝试使用 fetch api,也许我正在让 http 在 Vue 中调用错误的方式,我怎样才能获取我的数据并解决这个错误?
Here is my component:这是我的组件:
<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>
and my vue.config.js
:和我的vue.config.js
:
module.exports = {
devServer: {
proxy: 'base-url',
}
}
I think you may need to set up a middleware in the endpoint you are calling such as following:我认为您可能需要在您调用的端点中设置一个中间件,如下所示:
// 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();
});
Please try to add this to your endpoint API you are calling from so that new calls can be authorized.请尝试将此添加到您正在调用的端点 API 以便可以授权新呼叫。
Your should have 'Access-Control-Allow-Origin: ' Header你应该有 'Access-Control-Allow-Origin: ' Header
so make sure that your [api base url] returns this header to make your browser allow your request to go through without being (as way of protection)所以请确保您的 [api base url] 返回此 header 以使您的浏览器允许您对 go 的请求通过而不被(作为保护方式)
More information about Access-Control-Allow-Origin有关访问控制允许来源的更多信息
An Example in PHP: PHP 中的示例:
<?php
header('Access-Control-Allow-Origin: *') // to allow all sites
... the rest of the code
In the recent versions of vuejs, for example if the remote api is at http://localhost:9002/tasks then use server config.在最新版本的 vuejs 中,例如,如果远程 api 位于 http://localhost:9002/tasks,则使用服务器配置。
// vite.config.js
import { defineConfig } from 'vite'
export default defineConfig({
server: {
proxy: {
'/tasks': 'http://localhost:9002'
}
}
})
I found out what I was doing wrong, after setting up the proxy I had to change my get request to我发现我做错了什么,在设置代理后,我不得不将我的获取请求更改为
mounted() {
axios
.get(
"http://localhost:8080/https://base-url"
)
.then(response => console.log(response));
That fixed the issue.这解决了这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.