Reputation: 566
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?
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
:
module.exports = {
devServer: {
proxy: 'base-url',
}
}
Upvotes: 4
Views: 11492
Reputation: 1293
In the recent versions of vuejs, for example if the remote api is at http://localhost:9002/tasks then use server config.
// vite.config.js
import { defineConfig } from 'vite'
export default defineConfig({
server: {
proxy: {
'/tasks': 'http://localhost:9002'
}
}
})
Upvotes: 0
Reputation: 566
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.
Upvotes: -1
Reputation: 88
Do you have the header configuration setup for cors in your vue.config? Should look something like this.
Upvotes: 2
Reputation: 11
Your should have '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)
More information about Access-Control-Allow-Origin
An Example in PHP:
<?php
header('Access-Control-Allow-Origin: *') // to allow all sites
... the rest of the code
Upvotes: 1
Reputation: 91
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.
Upvotes: 1