[英]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.